Wednesday, November 11, 2009

Passwordless SSH made easy

Every six months, Ubuntu comes out with a new version. Each time that happens I always end up doing a fresh install, rather than taking the chances of an upgrade gone wrong. This means that every six months, I have to set up certain things all over again. The only thing I keep from one install to the next is my Firefox profile, and my "~/home/me/pictures" directory.

One of the things that always gets me is setting up SSH keys so I can log into my various shells without needing to type a password. So instead of this:

chris@chris-comp:~$ ssh chris@myshell.com
password for chris@myshell.com:
chris@myshell:~$


I can just do this:

chris@chris-comp:~$ ssh myshell
chris@myshell:~$


How to do it



First lets add a ssh "bookmark". Add the following to a file called "config" in your .ssh directory:

chris@chris-comp:~$ vim ~/.ssh/config
...


Host myshell
User chris
HostName myshell.com



This basically sets up an alias that lets you use "myshell" in place of "chris@myshell.com". This alias works anywhere on the system, including scp:

chris@chris-comp:~$ scp ~/myfile.txt myshell:~/



If you use Ubuntu, you can go to Places -> Connect to Server, then select "ssh" in the dropdown menu. Under server, just enter "myshell". This will allow you to browse the contents of that ssh machine in Nautilus! Pretty cool! Now you can drag and drop stuff from your ssh machine into apps on your desktop!

Creating the keys


Now, lets create our keys, run the ssh-keygen command:

chris@chris-comp:~$ ssh-keygen -t rsa -C "me@email.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/chris/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/chris/.ssh/id_rsa.
Your public key has been saved in /home/chris/.ssh/id_rsaub.
The key fingerprint is:
01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db me@email.com


This command basically creates both a private key and a public key for you, and places it in the /.ssh directory in your home directory. The idea is that you place the public key onto any server's you want to connect to. When you connect to that server, it will check the public key you gave it against your private key. If it matches, you're let in. Otherwise it'll ask you for a password.

Now that we've created the keys, lets add them to our server. Googling around the internet brings up a lot of ways to do this, but by far the easiest is this:

chris@chris-comp:~$ ssh-copy-id -i .ssh/id_rsa.pub myshell


This command will copy your public key over to the machine's public key holder place (.ssh/id_rsa.pub).

If all went well, you can connect to your ssh host without needing a password:

chris@chris-comp:~$ ssh myshell
chris@myshell:~$


Yay!