Generating an ssh key
Generating the ssh key in Linux is simple, use the ssh-keygen command.
[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:
The key's randomart image is:
| . |
| . p= o |
|..=+o* . |
|o=+.l.. S |
|=*.* . |
|XBo+ o. |
|EO oB=o |
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:
[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,
ssh-copy-id -i ~/.ssh/id_rsa.pub admin@devopsrun2
Give yes to continue
[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
And provide the password for admin@devopsrun2 when prompted.
/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
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.
Your ssh key has been successfully copied to the remote server. Let us try login to devopsrun2 server as admin
[root@devopsrun1 ~]# ssh admin@devopsrun2
Last login: Mon XXX XX 13:40:10 2019 from gateway
In this example, you have successfully configured ssh-key based authentication from devopsrun1 to devopsrun2
How to execute multiple commands on a remote server using ssh?