1、生成公钥
首先检查主机是否存在公钥:
进入./ssh目录,查询是否存在 id_rsa 和 id_rsa.pub(公钥)。
[root@server1 ~]# cd .ssh/
[root@server1 .ssh]# ll
总用量 16
-rw-r--r-- 1 root root 802 5月 22 10:35 authorized_keys
-rw------- 1 root root 1675 5月 22 10:34 id_rsa
-rw-r--r-- 1 root root 394 5月 22 10:34 id_rsa.pub
-rw-r--r-- 1 root root 522 5月 20 16:31 known_hosts
如果公钥不存在,需要生成公钥:
使用命令 ssh-keygen 生成公钥,在后续的回显中一路Enter
[root@host199 ~]# 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:2CQOB8XnJktJnasdTcTr2J9fI9k4iZufr0tJfUBnK9s root@host199
The key's randomart image is:
+---[RSA 2048]----+
| .o.. +. . o|
| .o + o . o.|
| ..o+.+ . ... |
| ++== o =. |
| .o*S= o E.|
| o o o o * .|
| o X o.|
| * +..|
| o.*=. |
+----[SHA256]-----+
2、对目标主机设置免密
使用命令 ssh-copy-id <ip> 对目标主机设置免密。ip为目标主机的ip。
命令回显需输入目标主机的密码。
[root@host199 ~]# ssh-copy-id 10.1.104.188
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/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
[email protected]'s password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '10.1.104.188'"
and check to make sure that only the key(s) you wanted were added.
此时,主机10.1.104.188对当前主机免密。
使用ssh测试一下:
[root@host199 ~]# ssh [email protected]
Last login: Thu May 28 18:53:33 2020 from 10.2.3.200
[root@server1 ~]#
⚠️ 注意:如果要实现双向免密,需要在目标主机上重复操作一次即可。