Setup SSH Keys with ssh-copy-id

In the article below, you can find quick and easy explanation how to generate and setup ssh keys between two hosts.
SSH keys have two major benefits – added security and easier management of multiple hosts with one public key. Nowadays, it gets more and more popular with the eve of the Automation era – you know, keeping THE passwords in a file is not the best security.

On the machine that we want to connect from, most commonly our workstation or Ansible master, we have to generate SSH key pair:

root@cb-master:~# ssh-keygen -t rsa

You will receive the following output:

Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/
The key fingerprint is:
SHA256:GlrrDh2dVB2xnyfJT0SuuBGUV2k8Sw4n0kGnz1aVc7o root@cb
The key’s randomart image is:
+—[RSA 2048]—-+
| ..**oo*|
| . oo=+%o|
| . +oB.O|
| o . =+B.|
| + S o B=o|
| + = oE= |
| o + . .|
| o |
| .o |

Perfect, now the only thing left is to transfer the public key to the host that we want to connect to.
Very important DO NOT ever share you private key – it is something that you have to keep secret.

First, let’s check what is in the .ssh/authorized_keys in the machine, that we are going to transfer our public key to:

root@cb-slave:~# cat .ssh/authorized_keys

Well, nothing – now, let’s transfer our public key (where yyy.yyy.yyy.yyy is the IP address of the remote machine):

root@cb-master:~# ssh-copy-id root@yyy.yyy.yyy.yyy

The result should be the following:

/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed — if you are prompted now it is to install the new keys
root@yyy.yyy.yyy.yyy’s password:

Number of key(s) added: 1

Now try logging into the machine, with: “ssh ‘root@yyy.yyy.yyy.yyy'”
and check to make sure that only the key(s) you wanted were added.

The magic behind is that ssh-copy-id login to the remote host, copy the public key and configure authorized_keys file, so it is adding your public key into the file.

If you try some of the following:

ssh ‘root@yyy.yyy.yyy.yyy’
ssh yyy.yyy.yyy.yyy

You won’t be prompted for password.

If you check the authorized_keys of the remote machine you will see:

root@cb-slave:~# cat .ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDuH85kXa2dmFHQR8CFKRGRKKbhL5EpFEDQU58IyA/fT8/5+Pn3XqGS7VMY3qIX4JlaR6/gRBCCUwNy/BqQ1DmaFqGtiuiqWwCphCC2nsDXePzuUvvlC2hThuEVrkbZE7lT9GKQj/X87LFNp45RJFHkLt2pc1hCQsp1314Zl4fPN5kwlc5s0jHxM5YpSVLQjHTiKrnoCqvDOMsMubiFIr6BB0gy1fGVhRVU/ynGOvsIiTT4IdPNCYeRI4MFyXgai08kOlLnFVceZ+WF/wCwhJRxwoL5+5PTSs5OIcHlc5JpSsYOzdwdy+GpgaYTbSX/Ou7Ha+ypP31pMDX0AIkx9aDD root@cb-master

Stay tuned, for other useful tutorials.
Secure your dreams on a solid ground.