Question: I’ve been assigned a task to automate file transfers between remote machines using scp. But I’m not sure how to give password as a parameter to the scp command. One of my friend suggested to use ‘sshpass‘ command (it can take password as an argument), but my boss says “sshpass is not the right way of doing it and it’s not secure“. What do you suggest?
– Ravi
Answer:
Ravi, your friend has the answer to your question, but your boss is right. ‘sshpass‘ utility takes password as an argument, but it’s less secure. Instead you should use SSH keys for secure file transfers.
Let us try out both the methods and see which is more secure.
Using sshpass
Install ‘sshpass‘ using the below command:
$ yum install sshpass Setting up Install Process Resolving Dependencies --> Running transaction check ---> Package sshpass.x86_64 0:1.05-1.el5 set to be updated --> Finished Dependency Resolution
Once installed, you can use it as below:
sshpass -p "password" scp file.txt user@remote_machine:
Caution: Since the password is mentioned in the command, it can be viewed by other users logged-in to the machine using ‘w‘ command. To prevent that, you can store the password in a file and pass the file as an argument to the command (shown below):
$ echo "password" > passfile.txt
$ chmod 600 passfile.txt
$ sshpass -f passfile.txt scp file.txt user@remote_machine:
Caution: The password can still be traced down from the log files or history.
So the verdict is “sshpass” is not a secure method. Instead, as your boss suggested, you should use Secure SSH keys for passwordless connections.
Using secure ssh keys
Generate ssh-keys on the source machine as below:
[machine-A ]$ ssh-keygen -t rsa
[machine-A ]$ scp ~/.ssh/id_rsa.pub user@machine-B:.ssh/authorized_keys
That’s it, you have setup ssh passwordless connection between machine-A and machine-B. Try transferring files without the need of entering password:
$ scp file.txt user@remote_machine:
Done! Ravi, sometimes BOSSES are right 🙂