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.
#!/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."
You have a few options other than using public key authentication:
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 !
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With