Dcapedcode

Copying SSH key to server (Linux)

Securely accessing your remote servers is crucial. This tutorial shows you two ways to copy your SSH public key to a target server: using the convenient ssh-copy-id command and a manual method for more control. Choose the method that best suits your needs and security preferences.

Requirements

  1. You will need an SSH key. If you don't have one, you can find a tutorial on how to create one here: Generate SSH key (Linux).

Using ssh-copy-id

Using ssh-copy-id makes this process very simple:

ssh-copy-id username@server_ip_or_hostname

Make sure to replace username and server_ip_or_hostname with an actual user on the server and the IP/hostname of the server.

Manual copying

Step 1 - Display public key

The filename will differ depending on what encryption type you used.

cat ~/.ssh/ed25519.pub

Copy the output to your clipboard.

Step 2 - Connect to your server

ssh username@server_ip_or_hostname

Replace username and server_ip_or_hostname with the appropriate values.

Step 3 - Add your SSH key

On the server, open the ~/.ssh/authorized_keys file:

vim ~/.ssh/authorized_keys

If the ~/.ssh directory or authorized_keys file does not exist, you may need to create them:

mkdir -p ~/.ssh touch
~/.ssh/authorized_keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

Paste your key into the authorized_keys file. Save and close the file.

Time to test SSH connection

Disconnect from the server and then try reconnecting using SSH to ensure the key-based authentication works:

ssh username@server_ip_or_hostname

You should not be prompted for a password if everything is set up correctly, unless you have set a password for your SSH key.