Permanently Add a Private SSH Key So It Persists After Reboot

Permanently add a private key to SSH

I think we have all been in a situation where we have to use an SSH key instead of the usual login and password. I remember being surprised that after a system reboot I had to add the key again with ssh-add before I could connect to the remote server. So today we will solve this problem. Let’s start! 😉

Problem: How to permanently add a private key, so it does not have to be added again after every reboot?

Solution: ssh-add puts the key into the SSH agent, and the agent forgets it when the session ends. Instead, tell the SSH client in ~/.ssh/config which key to use for which server. Then the key is read from the file on every connection.

Step 1. Where the keys are

By default the keys are in the .ssh folder of your home directory, for example /home/username/.ssh/id_rsa. To see which keys the agent has right now:

ssh-add -l

Step 2. Move the key to .ssh

Move your key (for example, a .pem file from the hosting or AWS) to ~/.ssh/ and make it readable only by you. With looser permissions SSH refuses to use the key:

mv ~/Downloads/our-key.pem ~/.ssh/
chmod 600 ~/.ssh/our-key.pem

Step 3. Add the host to ~/.ssh/config

Open the file ~/.ssh/config (create it if it does not exist; the name is config, without a dot) and add:

Host 8.8.8.8
    IdentityFile ~/.ssh/our-key.pem

where:

  • 8.8.8.8 is the address of the host; a domain name works too;
  • ~/.ssh/our-key.pem is the path to our key.

That’s all! Now ssh user@8.8.8.8 uses the key without ssh-add.

A short alias

In the same file you can give the server a name and set the user, so the command becomes just ssh myserver:

Host myserver
    HostName 8.8.8.8
    User ubuntu
    IdentityFile ~/.ssh/our-key.pem
    AddKeysToAgent yes

AddKeysToAgent yes adds the key to the agent at the first connection, so a key with a passphrase asks for it only once per session. On macOS also add UseKeychain yes, and the passphrase is stored in the Keychain.

NOTE: The ~/.ssh folder must have the permissions 700 and the config file 600, otherwise SSH may ignore them.

Sources:

  1. https://stackoverflow.com/questions/3466626/how-to-permanently-add-a-private-key-with-ssh-add-on-ubuntu