Wednesday 12 August 2009

HOWTO: Passwordless SSH using a public key

If you find yourself logging in to machines regularly or you want to include ssh commands in a script, for example using rsync to backup then you don't want to have to enter a password every time. In such cases you can use a public key.

The first thing we need to do is create a ssh key pair on the client host. Make sure that you login as the user who will be connecting to the server. In this case I am using the root user.
Warning: If your user already has a key pair then you should skip this step otherwise you may overwrite your existing key and potentially cause problems for other services that may already rely on them.

First, we should check whether there is already a keypair for our user;

ls -al ~/.ssh/
known_hosts


If there are files id_rsa and id_rsa.pub (or similar) listed then you already have a keypair and you should skip this step.

Creating an ssh key pair (press [enter] for each question asked);

ssh-keygen
Note: It is important that you don't enter a passphrase when asked to! If you did just run the command again, it will overwrite the key you just created.

You can check your new keys by looking in the .ssh folder

root@client:~# ls .ssh/
id_rsa id_rsa.pub known_hosts


The one we are interested in here is the public key which ends with .pub. We need to copy this file to /root on the server.
Note: You can do this via scp or copy it onto a thumbdrive or even type it in from a printout if you like! I will leave it up to you to decide the best method in your situation.

On the server, we will need to login as the root user;

Now, we should have the public key file that we copied earlier in our root directory. Let's double check that;

root@server:~# ls -al *.pub
-rw-r--r-- 1 root root 392 2010-08-02 08:22 id_rsa.pub


Great, it is there! We need to add this key to the root users authorized_keys file;

cat id_rsa.pub >> .ssh/authorized_keys

We can test that this worked by going back to our client PC and logging into the server via ssh;

root@client:~# ssh root@server
Linux server 2.6.32-25-generic-pae #44-Ubuntu SMP Fri Sep 17 21:57:48 UTC 2010 i686 GNU/Linux
Ubuntu 10.04.1 LTS

Welcome to Ubuntu!
* Documentation: https://help.ubuntu.com/
Last login: Thu Oct 14 15:38:57 2010 from client
root@server:~#


If it didn't ask you to enter a password then you are cooking with gas!

1 comment:

Anonymous said...

THanks for this.

Finally a no bs rundown, been meaning to do this for years at home. Keep the tips coming. Love the site.