1. Overview

Using SSH keys is a best practice when connecting to other machines securely. To use our SSH key pair, we have to copy the public key to the remote machine. In this tutorial, we’ll observe a few ways to do this. The examples we’ll show here assume that we’ve used ssh-keygen with default settings to create our SSH key pair. All examples have been tested in Bash and should work in other POSIX compatible shells as well.

2. On Our Machine

On our local machines, our SSH key pair is located under our home directory, in a subdirectory called .ssh:

drwx------   5 vagrant  vagrant   160 Apr 23 13:11 .ssh

The .ssh directory is only accessible for our own user and contains the actual key pair in two files:

$ ls -l .ssh
total 16
-rw-------  1 vagrant  vagrant  1843 Mar 27 15:09 id_rsa
-rw-r--r--  1 vagrant  vagrant   413 Mar 27 15:10 id_rsa.pub

The file called id_rsa contains our private key, and our public key is stored in id_rsa.pub. We need to copy the public key to the other machine in order to use this key pair to log in.

3. Manual Copy

First, we’ll take the manual approach. Let’s copy the public key to the other machine using the scp command. From our home directory, we run:

$ scp .ssh/id_rsa.pub our_username@other_machine:

We have to type our password for the remote machine, and the file is transferred. Then, we log in to the other machine also using our username and password to put the file in its right location. First, we have to make sure our home directory on the other machine also contains a directory called .ssh with the same access rights as the one on our own machine:

$ mkdir .ssh
$ chmod 700 .ssh

This directory should contain a file called authorized_keys that is accessible only to our own user:

$ touch .ssh/authorized_keys
$ chmod 644 .ssh/authorized_keys

The file should contain all public keys of the key pairs that we want to allow our user to log in with. Let’s append the public key we transferred to this file:

$ cat id_rsa.pub >> .ssh/authorized_keys

From now on, every time we log in to this other machine, our key pair is used, and we don’t have to enter our password anymore.

4. Using ssh-copy-id

The manual approach takes quite a few steps. Fortunately, Linux comes with a convenient script that does all the heavy lifting for us. This script is called ssh-copy-id. We simply run the following command:

$ ssh-copy-id our_username@other_machine

This will take our public key from its default location and transfer it to the other machine, performing all the same steps we did manually above.

5. Conclusion

In this article, we learned how to copy our SSH keys to other machines. When performing a manual copy, we need to make sure to set all file permissions as restrictive as possible. The easiest way to copy SSH keys is using the ssh-copy-id script.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.