Passwordless SSH logins

Printer-friendly versionPrinter-friendly version

To enable login to a remote machine by ssh without having to enter the password is a useful thing, and one I get asked about with some regularity. I'll describe two methods I use, one that uses ssh public keys with no passphrases, and the other using ssh-agent to store the passphrases of your keys.

To use ssh keys, you'll first need to have one. You can create this with the ssh-keygen utility like so:

ssh-keygen -t <algorithm> -b <bit size>

for example:

ssh-keygen -t rsa -b 4096

by default, ssh generates a 2048 bit key, but I usually like to use 4096 (paranoia and all). This will prompt you for where to save the files (the default is ~/.ssh/id_rsa.* for the above line) and also for a passphrase to use when reading it. If you opt to enter a passphrase, you'll need to re-enter it each time you want to establish an ssh connection. This can be good on a semi-public machine, and means that you still only have to remember the one password, instead of one for each machine you're connecting to, but it is moderately annoying. Generally, I don't use that, and just leave it empty (no passphrase). Assuming you've used the above line, you now need to copy the public key to the remote machine. This can be done with:

scp <options> ~/.ssh/id_rsa.pub <remote machine>
ssh <options> <remote machine>
cat id_rsa.pub >> .ssh/authorized_keys2
rm id_rsa.pub
exit

or, much more succinctly:

ssh <options> <remote machine> "echo '`cat ~/.ssh/id_rsa.pub`' >> .ssh/authorized_keys2"

This takes the contents of your ~/.ssh/id_rsa.pub file (your public key) and appends it to the end of your authorized_keys2 file on the remote machine. You want to be careful not to overwrite that file, since it can contain multiple public keys (i.e., one from every machine you log in from).

That's it! You should now be able to log into the remote machine without needing to supply a password! If it didn't work, you need to start checking permissions on your '.ssh' directory and the authorized_keys2 file on the remote machine. They should only be readable by your user on that machine.

If you have entered a passphrase for your ssh keys, you can add it to your session by running:

ssh-agent; ssh-add

This will start an ssh-agent, and ask you for any passphrases you have on your ssh keys. After entering them, you won't have to enter them again during this session.

For further tricks, see SSH-TO aliases for a way to take remote machines and make one-word aliases that you can use from the command line to establish an ssh session to them.

Brian

Search Engine Optimization