Tuesday, April 1, 2014

Passing authentication with SSHPASS

There is a requirement to create a cron script that will transfer files through SFTP command. But one problem I’m facing here is the script will prompt for password in order to proceed its job. This is not a correct behavior since a cron must be able to perform the task without human interaction.

Since the server is not yet ready for me to play around with, and I don’t know how to setup public/private key pair, the only way I can opt for is SSHPASS command. I think this should be the cheapest solution I could opt for. I do understand that SSHPASS is insecure and not encourage to use, but this should be fine under development stage.

Assuming I’m going to transfer a file to a destiny location at /home/theuser with username theuser and IP 123.123.12.123. With SFTP, this is what I’ll do in the script:
sftp theuser@123.123.12.123:/home/theuser << EOF
put thefile.txt
bye
EOF
Whenever this script is run, I’ll get a prompt for password then only the process will continue. Now if I do it with SSHPASS command, this is how it look like:
sshpass –p ‘password’ sftp theuser@123.123.12.123:/home/theuser << EOF
put thefile.txt
bye
EOF
There is also an alternate solution as shown below, by keeping the password in environment variable but which is strongly not a good way to go.
export SSHPASS=password
sshpass –e sftp theuser@123.123.12.123:/home/theuser << EOF
put thefile.txt
bye
EOF

1 comment:

Robin Whittle said...

Thanks very much for your article. Another way of handling the password, so it doesn't appear on any command lines and so would not be visible via ps to non-root users, is to create a file xyz which contains just the password, and make this read write for root, but not for others: 600.

Then, instead of "-p" option to provide the password to sshpass or the use of an environment variable, use "-fxyz".