Simplifying server logins with SSH keys

And transferring them with ssh-copy-id

Posted by Matthias Schmidt on January 16, 2015

Developing applications means dealing with remote servers at some point. And dealing with remote servers means coming across SSH sooner or later. And using SSH often means remembering logins and passwords. But not only is a password something you need to remember, it’s also something not as secure as it should be. Well most of the time at least. I’m talking about choosing simple passwords to make them easier to remember or using the same all over the place. Or both.

I’ve come to a point where I need to handle quite a lot of servers and all of them use SSH. Regardless of the amount of servers you have to deal with you should use SSH keys instead of passwords as means of authorization.

SSH keys

SSH keys are pairs of keys always consisting of a private key as well as a public key. You could compare the private one to a physical key and the public one to a physical lock. It’s possible to install the same kind of lock all over the place but you have to keep the matching key well protected to yourself.

It’s easy to generate a key pair with OpenSSL:

$ ssh-keygen -t rsa -C "[email protected]"
// you'll find the generated keys here:
~/.ssh/id_rsa
~/.ssh/id_rsa.pub

Now you can install the public key on all your servers while keeping the private one on your machine.

To install the public key on a server you have to copy the key into ~/.ssh/authorized_keys on the remote machine. It’s possible to do this by hand for every server & user you’d like to use but I’d recommend using ssh-copy-id.

ssh-copy-id

ssh-copy-id is a small tool that takes care of transferring your public key from your local machine to the server of designation.

Just run the tool and you are all good to go:

$ ssh-copy-id [email protected]

Remember to repeat this for every user account you’d like to access through SSH.

In case you receive an error about ssh-copy-id not being found just install it with your trusted package manager. It’s available for all kinds of systems. For Mac OS X with Homebrew the command to install ssh-copy-id would look like this:

$ brew install ssh-copy-id

Disabling password authentication

Once your keys are installed you should disable password authorization for SSH on your remote machines. If this is not an option you could change your password to something long and complex.

To disable SSH password login edit /etc/ssh/sshd_config and add or change the following settings:

ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no

Once you have SSH key authorization set up you won’t go back.