Generating an ssh key


Generating the ssh key in Linux is simple, use the ssh-keygen command.
Example:
Code:
[root@devopsrun1 ~]# ssh-keygen
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/id_rsa.pub.
The key fingerprint is:
SHA256:KSiVJyeOaAuP7nrve84Iv2CJJkN0D46p02lJKyvTgrM root@devopsrun1
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|     .           |
| . p= o          |
|..=+o*   .       |
|o=+.l.. S        |
|=*.*   .         |
|X+%              |
|XBo+ o.          |
|EO oB=o          |
+----[SHA256]-----+
[root@devopsrun1 ~]#

Where is my public key file?


Your public key will be stored in your home -> .ssh directory.
From the example above, the key is stored in as /root/.ssh/id_rsa.pub:
Code:
[root@devopsrun1 ~]# ls -l /root/.ssh/id_rsa.pub
-rw-r--r-- 1 root root 397 XXX XX 15:16 /root/.ssh/id_rsa.pub

How to copy ssh public key to another server?


You can use the ssh-copy-id command with specific arguments such as the public key file path and remote server details for copying to another server,
Code:
ssh-copy-id -i ~/.ssh/id_rsa.pub admin@devopsrun2

Example:
Code:
[root@devopsrun1 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub admin@devopsrun2
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host 'devopsrun2 (10.0.2.15)' can't be established.
ECDSA key fingerprint is SHA256:5ehZuK7FcKI58XykbXJuWcqsnBP4UGO+gYwhT+Enjm4.
ECDSA key fingerprint is MD5:65:49:d1:70:9f:86:f4:a0:fc:ed:c9:16:8e:00:cd:bb.
Are you sure you want to continue connecting (yes/no)? yes
Give yes to continue
And provide the password for admin@devopsrun2 when prompted.
Code:
/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
admin@devopsrun2's password:

Number of key(s) added: 1

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

[root@devopsrun1 ~]#

Your ssh key has been successfully copied to the remote server. Let us try login to devopsrun2 server as admin
Code:
[root@devopsrun1 ~]# ssh admin@devopsrun2
Last login: Mon XXX XX 13:40:10 2019 from gateway
[admin@devopsrun2 ~]$
Congratulations!
In this example, you have successfully configured ssh-key based authentication from devopsrun1 to devopsrun2

Related topics:
How to execute multiple commands on a remote server using ssh?