Tuesday, May 8, 2007

Passwordless log in with SSH keys

    A very fine feature of UNIX operating systems is native support for services like SSHd. SSH provides shell access on remote computers - encrypted, so no one can snoop your passwords. SSH comes with various utilities including scp, which allows you to copy files and folders to the remote server (and all this traffic and data is encrypted). You can also use ssh as rsync's transport mechanism for synchronizing directories across computers. If you want to automate tasks like this (scheduling unattended backups with cron, for example), you'll need the computer that's initiating the connection to be able to log into the remote computer without being prompted for a user to input a password.

This is where ssh 'keys" come in. You create a private/public key pair on your computer ("the client"), and put the "public" key up on the remote computer ("the server"). After that, when you log into the remote computer, you are no longer prompted to enter a password (so long as you made the key correctly).

To generate a pair of keys with no passwords, using the standard RSA type of keys, run the following command on the computer you are connecting from:

    ssh-keygen -t rsa -N ""

This will create two files: ~/.ssh/id_rsa and ~/.ssh/id_rsa.pub
Copy - with scp - the public file ~/.ssh/id_rsa.pub up to the remote computer you will be connecting to (or sending data to). Then log into the remote server and put the contents of that public key into the ~/.ssh/authorized_keys file. An easy way to do that is like this:

    cat >> id_rsa.pub ~/.ssh/authorized_keys

Using the double "greater than" brackets ensures that if ~/.ssh/authorized_keys already exists, the new key will be added to the file, and not overwrite any existing keys that might already be in place.

After that, you should be able to connect from the client with the key pair to the remote server without being prompted for a password.

No comments: