How to Add SSH Keys to Remote Server

After generating ssh keys, we have to add public key to remote server before we use them. In this post, I will quickguide how to add ssh keys to remote server.

Add SSH Keys with ssh-copy-id Utility

The ssh-copy-id utility is pre-installed on most Linux distributions. macOS users can install it via Homebrew.

$ ssh-copy-id -i ~/.ssh/id_rsa.pub root@11.22.33.44
  • Specify the correct public key with the -i [path to public key] parameter.
  • Specify the username and server IP address (or domain name) as shown. For example, the root user at 11.22.33.44.

The utility will print some basic information and prompt for your password, enter your password and the utility will install ssh key to remote server.

Add SSH Keys Manually

Log into your remote server using password authentication and create the ~/.ssh/ directory if it does not already exist.

mkdir -p ~/.ssh

You'll need to append your SSH Key ( public key ) to an authorized_keys file in this directory, create it if it does not already exist, then update permissions of the files. The ~/.ssh directory and authorized_keys file must have specific restricted permissions (700 for ~/.ssh and 600 for authorized_keys). If they don't, you won't be able to log in.

chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh/

If you created those file with either root or your own admin accounts for some other user, you need to change the ownership to the user:

chown -R username:username /home/username/.ssh

Replace username with the real user name, and now you can log into your server with SSH Key.