How To Generate An SSH Key and Add The Public Key To A Remote Server

The thing with SSH authentication is I can never remember the steps to generate an SSH key, and then add that SSH public key to the remote server so SSH authentication works.

I had all of this in a text file, but honestly, I reference my own blog for knowledge on how to do things all of the time, I thought I’d write up a quick post.

You can find numerous blog posts on this, but I always seem to find a straightforward explanation to give me what I need, that I just consulted my text file on my desktop.

Generating An SSH Key

This will generate both private and public keypairs.

ssh-keygen -t rsa -b 4096 -C "johnsmith@gmail.com"
# Generates a new private and public keypair, using the email as the label

You’ll be asked to enter a keyphrase. Personally, I don’t use keyphrases for my keys (I know I probably should). So, I skip the following.

Enter passphrase (empty for no passphrase):
Enter same passphrase again:

For the key names, by default it’ll generate id_rsa and id_rsa.pub but you can name these whatever you want. Because I am dealing with CI providers like Travis CI and GitHub Actions, I generate keys every time I do something with a server.

Add Your Public Key To The Remote Server

Basically, we copy the contents of the public key and store it in the authorized_keys file in the .ssh folder on the server.

cat ~/.ssh/id\_rsa.pub | ssh username@domain.com 'cat >> ~/.ssh/authorized\_keys'

If you kept the default name, keep id_rsa.pub as the key name. For username@domain.com add in your server username and the server domain name or IP address. The second string part just copies the contents of the file into the authorized_keys file on the server.