How to SSH using a public key instead of password

When accessing remote systems using SSH it can be handy to use RSA keys rather than having to enter a password every time. Especially handy if doing automation using Ansible or similar tools. Here’s how to do it:

Generate the key pair
One public and one private key will be created. The private key is kept securely on the client system. The public key is copied to the target server. The passphrase is optional. It helps secure they key if the private key is compromised. In this example we skip entering a passphrase.

jonas@nyx:~$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/jonas/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/jonas/.ssh/id_rsa.
Your public key has been saved in /home/jonas/.ssh/
The key fingerprint is:
68:1f:bd:d2:80:3e:ad:fa:f0:eb:c0:2f:a2:23:8d:5a jonas@nyx
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|                 |
|                 |
|       o .       |
|      + S .      |
|   . o o + .     |
| oE + o + o      |
|+.o .= o .       |
|=o ..=B.         |

Copy the key to the remote system
We now copy over the public key to the remote system. Note that we need to enter the password to get the key copied. This is what we’re trying to fix. Note that we copy the .pub public key to a new name: “authorized_keys” in the .ssh directory for your user on the remote system. For example “/home/jonas/.ssh/authorized_keys”.

jonas@nyx:~$ scp ~/.ssh/
jonas@'s password:                                                 100%  391     0.4KB/s   00:00    

Verify the solution
Repeat the SCP command but this time copy the public key to a random name to verify that SSH/SCP can be done without entering a password:

jonas@nyx:~$ scp ~/.ssh/                                                 100%  391     0.4KB/s   00:00    

…and with Ansible
Below we finally compare pinging a host with RSA key auth enabled vs. server with password login only. Predictably one succeeds and one fails.

jonas@nyx:~$ ansible -m ping all | success >> {
    "changed": false, 
    "ping": "pong"
} | FAILED => SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue

Leave a Reply