Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run the sftp command with a password from Bash script?

I need to transfer a log file to a remote host using sftp from a Linux host. I have been provided credentials for the same from my operations group. However, since I don't have control over other host, I cannot generate and share RSA keys with the other host.

So is there a way to run the sftp command (with the username/password provided) from inside the Bash script through a cron job?

I found a similar Stack Overflow question, Specify password to sftp in a Bash script, but there was no satisfactory answer to my problem.

like image 353
anubhava Avatar asked Mar 22 '11 03:03

anubhava


People also ask

How do I prompt a password in bash?

#!/bin/bash echo "Enter Username : " # read username and echo username in terminal read username echo "Enter Password : " # password is read in silent mode i.e. it will # show nothing instead of password. read -s password echo echo "Your password is read in silent mode."


2 Answers

You have a few options other than using public key authentication:

  1. Use keychain
  2. Use sshpass (less secured but probably that meets your requirement)
  3. Use expect (least secured and more coding needed)

If you decide to give sshpass a chance here is a working script snippet to do so:

export SSHPASS=your-password-here sshpass -e sftp -oBatchMode=no -b - sftp-user@remote-host << !    cd incoming    put your-log-file.log    bye ! 
like image 200
anubhava Avatar answered Oct 01 '22 08:10

anubhava


Another way would be to use lftp:

lftp sftp://user:password@host  -e "put local-file.name; bye" 

The disadvantage of this method is that other users on the computer can read the password from tools like ps and that the password can become part of your shell history.

A more secure alternative which is available since LFTP 4.5.0 is setting the LFTP_PASSWORD environment variable and executing lftp with --env-password. Here's a full example:

export LFTP_PASSWORD="just_an_example" lftp --env-password sftp://user@host  -e "put local-file.name; bye"  # Destroy password after use export LFTP_PASSWORD="" 

LFTP also includes a cool mirroring feature (can include delete after confirmed transfer --Remove-source-files):

lftp -e 'mirror -R /local/log/path/ /remote/path/' --env-password -u user sftp.foo.com 
like image 41
Karassik Avatar answered Oct 01 '22 09:10

Karassik