Andrew J. Nelson
10 April 2013
It is often desirable to authenticate to a remote host via SSH without having to enter the password, most often when you want to execute SSH commands from a shell script without human interaction. The safe and secure way to do this is to generate pre-shared keys between the two hosts.
It is assumed that the user has Slackware Linux installed on two hosts and network connectivity between the hosts. Furthermore, it is assumed the user has at least some familiarity with navigating in a Slackware shell environment. This How To was written using Slackware64 14.0 as the OS and the BASH shell environment. Every shell command necessary to completing the objective is provided, however, they are not explained in detail. Doing so is beyond the scope of this tutorial.
We will generate RSA encryption keys. You can read more about how RSA works at the RSA algorithm wiki page. The command to generate the keys is shown below, and you can see a screenshot of the expected output to the right. If you want to know more about the command, this is the ssh-keygen man page.
The keys should be generated in your account's home/.ssh directory. When prompted for the file, just hit enter to accept the default. When prompted for the passphrase, leave it blank. Per the ssh-keygen man page, host keys must have an empty passphrase.
ssh-keygen -t rsa
The ssh key generation created a private key (id_rsa) and a public key (id_rsa.pub). You will notice in the screenshot that I generated the key as root, which is not recommended. (That was done on a Slax session purely for the point of taking that screenshot.) Generally, you do not want to allow remote access to a machine as root.
Let's say however that you generated the key as user "webdev" on host "stagingserver". You want to be able to ssh into the production server without having to use the password. Your username on the production server is "webupdater" on host "prodserver".
We'll copy the contents of the id_rsa.pub on stagingserver and concatenate them to the file "authorized_keys" on prodserver, which should live in your account's home/.ssh directory. After the public key is copied over, you will be able to ssh into prodserver from stagingserver as webupdater without passing your password.
cat .ssh/id_rsa.pub | ssh webupdater@prodserver 'cat >> .ssh/authorized_keys'
You will be asked for your password when you run the cat, but after that it will no longer be neccessary.
With the public key for the account shared, you will be able to execute ssh commands within shell scripts without having to enter a password, which is very helpful for things like remote backups or updating websites. You can also create fast aliases for connecting to the host.
If you have any questions, concerns, suggestions, or constructive criticism, please email me.