Automating SSH for Scripting
Every time I create a new script to automate some mindless task of mine that
requires logging into remote hosts via ssh (for remote execution, file
uploading/downloading via sftp, etc.) I forget how to setup SSH such that I
don't have to use a password. I always remember the general "idea" (whatever
that means) but I forget the specifics, and have to dig through numerous
man pages before finally figuring it out.
problem:
You want to use SSH in some automated script, but you're always being prompted
for a password.
solution:
The solution is simple. You want to automate the task of authentication with
SSH. This is done via public/private key pairs. As an example, let's
suppose that user worf on machine pagh wants to be
able to login as user picard on the machine
enterprise.
First, as user worf on the machine pagh, generate a
public/private key pair by doing the following:
# ssh-keygen -t dsaThe
-t dsa specifies the type of keys you want to create, and can
be either rsa or dsa. You'll then be asked where
you would like SSH to save the keys. The default is
/home/worf/.ssh/id_dsa, and should be fine (just hit
enter). Next, you'll be asked for a passphrase. Don't enter one! That's the
whole reason you're creating these keys! To keep the passphrase empty, just
hit enter. Finally, you'll be asked to enter the same passphrase again, and
(just as before) hit enter to keep it empty. You then should see some
confirmation that the keys are built and saved appropriately, such as
Your identification has been saved in /home/worf/.ssh/id_dsa. Your public key has been saved in /home/worf/.ssh/id_dsa.pub.Next, you need to copy the public key to Picard's account on the machine you want to be able to login to. Copy it there however you'd like, such as
# scp /home/worf/.ssh/id_dsa.pub picard@enterprise:/home/picardFinally, you just need to add the public key to Picard's list of authorized keys, by doing the following:
# cat /home/picard/id_dsa.pub >> /home/picard/.ssh/authorized_keysYou should now be able, as user
worf on the machine
pagh, to login as user picard on the machine
enterprise via ssh/scp/sftp without being prompted
for a password.