Automatically logging in with SSH

I've done this dozens of times, but always forget, so it's time to do it in a slightly more robust manner.

When I ssh from machine A to B, it asks for a password. With public-key authentication, it's possible to set this up so it doesn't need a password to verify I am who I say I am. If I'm running scripts on a machine automatically that connect to another machine - say, for an rsync backup - I just want the scripts to run, not to have to stop for user input of a password.

Doing this takes a few steps... but is pretty darn easy. For two machines, client and server...

  1. Create a public ssh key on the client machine. You might even have one already. The directory where ssh stores it's files is ~/.ssh. The public key would be called either or If neither of those files are there, create one by typing "ssh-keygen -t rsa". Save the file in the default location, and enter no passphrase. (If you enter one, you need to retype it every time you use this key, which defeats the purpose in this case.) This should create a 2048-bit RSA private key.
  2. ssh is very, very particular about the permissions on the ~/.ssh directory, and for some operating systems (OS/X, Cygwin), the permissions often aren't already set correctly. "chmod 600 ~/.ssh" should do the trick, giving just the owner of the directory read and write access. I usually skip this step, and if an error occurs, come back to it.
  3. We need to copy the public ssh key (~/.ssh/ to the remote server, and append it to the authorized keys file (~/.ssh/authorized_keys, on the server). This should do the trick: "cat ~/.ssh/ | ssh 'cat >> .ssh/authorized_keys'" Be careful to copy, and not id_rsa; the latter is your private key, and you shouldn't copy it anywhere!
That's it. Test it out. I may work on getting it going inside of Putty at a later date, but for now, having it work on the command line is fine.

The main security problem I see with this is that if someone else has root or administrator access on a machine you've set up as a client, they can log into the server as you. If anyone gets access to your private key, they can also log in as you. Do *not* give out the private key.

No comments: