一共需要两步:第一步在host01主机中生成公钥和私钥,第二步将host01主机生成的公钥发给host02主机保存到指定文件中(~/.ssh/authorized_keys)。这样host01访问host02就不需要输入密码了,直接访问了。
第一步:生成SSH密钥文件(公钥和私钥):ssh-keygen
[root@host01l ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 直接回车,以默认路径保存
Created directory '/root/.ssh'.
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:tUB6SjLnvqM7p2l+bmHUZGNqUyyOPmXGyiMp3tC9xNA root@linuxcool.com
The key's randomart image is:
+---[RSA 2048]----+
| .. |
| .oB |
| +++Oo.. |
| ..E@o.o . |
| .++Bo.S . |
|..o.*=o |
|..o..+o. |
| . .oo=. |
| o*Xo. |
+----[SHA256]-----+
第二步:将公钥发给对方主机
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.3.202
[root@host1 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.3.202
/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 ins
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the
root@192.168.3.202's password: 这里提示需要输入host02密码即可
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.3.202'"
and check to make sure that only the key(s) you wanted were added.
host1公钥会默认保存到host2的~/.ssh/authorized_keys中
以上两步完成后,host01 ssh登录访问host2就不需要输入密码了
[root@host1 ~]# ssh 192.168.3.202 Last login: Tue Oct 11 21:51:11 2022 from 192.168.3.201 [root@host2 ~]#
(同样host2想免密登录host1也需要同样操作即可)