How to use scp in a bash script without specifying password?
Matthew Martinez
I am a bash newbie, and am writing a bash script that will allow transfer of files between two computers. BTW, is there a more secure alternative to scp?
Currently, I am doing this manually, by using scp. The remote server always prompts me for the password, and I supply that. I want to automate this (hence the bash script). However, I dont want to supply my password in plain text (or if at all - I was under the impression that open SSL does away with passwords and uses certificates etc?).
Can anyone please explain how I can automate my current process, without explicitly displaying my password.
I am running on Ubuntu 10.0.4
3 Answers
To login without password you need to setup key-based authentication. There are a number of tutorials out there - this one looks like a good place to start (edit: the original site fell of the Internet, this link is to the last copy archived by the WayBackMachine).
If you put a passphrase on your key (recommended) you will still need to provide that when you login but you can use ssh-agent to reduce the amount of times you have to provide it.
If you need scripts that use SSH/SCP to run unattended then you need to not have a passphrase on your key, but in this case you absolutely must keep that key file secure such that no-one else can read it otherwise they will be able to authenticate on that server as you without any password/passphrase.
3supply a password to scp
Piping your password to the standard input of scp won't work:
echo "password" | scp file user@host:/dir/to/copy/tobecause scp doesn't read from the standard input for security reasons.
Use the tool sshpass instead:
You may have to install sshpass as root since it is non standard.
sshpass -p 'mypassword' scp -r :/home/a/moo.txt /home/b/bar.txt If you use a key like .pem etc (so you wouldn't have to have a password) you could use this
here's bash code for SCP with a .pem key file. Just save it to a script.sh file then run with 'sh script.sh'
Enjoy
#!/bin/bash
#Error function
function die(){
echo "$1"
exit 1
}
Host=ec2-53-298-45-63.us-west-1.compute.amazonaws.com
User=ubuntu
#Directory at sent destination
SendDirectory=scp
#File to send at host
FileName=filetosend.txt
#Key file
Key=MyKeyFile.pem
echo "Aperture in Process...";
scp -i $Key $FileName $User@$Host:$SendDirectory || \
die "@@@@@@@Houston we have problem"
echo "########Aperture Complete#########";