How to Setup SSH keys for “passwordless” SSH Login on CentOS/RHEL

The post outlines the steps to configure passwordless ssh between 2 CentOS/RHEL hosts. The steps although remains almost the same with slight changes across all the Linux distributions.

1. Log in as the user that you want to set up the ssh keys, in this case, we are using user “geek”.

2. Create a private and public key :

$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/geek/.ssh/id_rsa):
Created directory '/home/geek/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/geek/.ssh/id_rsa.
Your public key has been saved in /home/geek/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:joc/+DIFmDiSD9qc/ZuF5I/iA1ghBK+f3niOnbfYFrk geek@node01
The key's randomart image is:
+---[RSA 2048]----+
|+.               |
|...              |
| o.o o           |
|+.+ o .          |
|oO +  .oS        |
|o.*..oo=.        |
|  o. .==+        |
| . =++EB.        |
|  ++B=**+.       |
+----[SHA256]-----+

Note:

You can specify an option on the ssh-keygen like the size and the type. More information on the man ssh-keygen

-b bits
Specifies the number of bits in the key to create. For RSA keys, the minimum size is 768 bits and the default is 2048 bits. Generally, 2048 bits is considered sufficient. DSA keys must be exactly 1024 bits as specified by FIPS 186-2.

-t type
Specifies the type of key to create. The possible values are “rsa1” for protocol version 1 and “dsa”, “ecdsa” or “rsa” for protocol version 2.

3. New Keys will be located on /home/geek/.ssh. Move to the .ssh directory were the key was created and verify:

$ cd .ssh
$ ls
id_rsa id_rsa.pub

4. Copy the public key to the target server (node02)

$[geek@node01 .ssh]$ ssh-copy-id -i id_rsa.pub geek@node02
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
The authenticity of host 'node02 (192.168.1.12)' can't be established.
ECDSA key fingerprint is SHA256:PJplQZl2GQqpoJDK7d4nubIP65/A6YyKBGSSaObvzXo.
ECDSA key fingerprint is MD5:a1:53:e6:d8:9a:71:47:ba:86:a1:d5:d2:25:4c:7c:3b.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
geek@node02's password:

Number of key(s) added: 1

Now try logging into the machine, with "ssh 'geek@node02'"
and check to make sure that only the key(s) you wanted were added.

5. Now test your key, you should login directly yo target server.

[geek@node01 .ssh]$ ssh geek@node02
[geek@node02 ~]$

Note: if your server has not installed openssh-clients package another alternative will be :

$ cat id_rsa.pub | ssh user@node02 "cat >> ~/.ssh/authorized_keys"
Related Post