SSH authentication via public key

This little guide explains how to setup SSH authentication via public key (so, without password requests in dialog).

That’s not only the safest method for access an SSH remote machine, but it’s also a way to automate tasks (eg. remote commands or data transfer) without the need for user action.

The basic principle is the key exchange (typically RSA keys) between hosts. If host A need to access to host B, then the public key of host A must be added in the list of authorized key of host B.

So, at first, you need to generate an authentication key on host A. You can use the simple ssh-keygen tool, issuing the command ssh-keygen -t rsa

A passphrase is asked during the keys generation. Enter a passphrase only if you want that this passphrase will be asked every time you use these keys (typically you’ll left empty the passphrase).

The command saves the key pair in .ssh  directory, into your home by default:

  • id_rsa  is the private key of host A
  • id_rsa.pub  is the public key that you have to insert on host B (and on all hosts you want to access via key authentication)

Now you have to append the content of id_rsa.pub into the ~/.ssh/authorized_keys  file on the user’s home of host B.

You can do it in different way, but the most elegant (in my point of view) is by using this single command:

cat ~/.ssh/id_rsa.pub |ssh <username>@<host B> \
"mkdir -p ~/.ssh && \
cat >> ~/.ssh/authorized_keys && \
cp ~/.ssh/authorized_keys ~/.ssh/authorized_keys2 && \
chmod 700 ~/.ssh && \
chmod 640 ~/.ssh/authorized_keys*"

The ~/.ssh/authorized_keys2  file will also be created, for compatibility with SSH version 2.

Now you should be able to login from host A to host B without any password request (or with passphrase request, if you’ve used one during key pair’s creation).

 

Note: the key authentication works at user level, therefore a key pair must be generated (and, obviously, added to authorized_keys ) for every users on host A that wants to use key authentication to host B. This also applies to host B, so a public key from host A must be added to ~/.ssh/authorized_keys  of every user’s home on host B that have to accept key authentication from host A.