ssh实现当前主机免密登录到其他主机

一、环境介绍

主机 IP
v2 192.168.78.102
v3 192.168.78.103
v4 192.168.78.104

 

二、实现在v2主机使用ssh免密登录到v3

1、在当前主机上生成ssh公钥和私钥
# 在v2主机上执行
[root@v2 ~]# ssh-keygen
# 执行返回结果
[root@v2 ~]# 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:dKcCKMg+vLgww6KPeoyJDK4Gw/m6CFL7uBv/mASfCy8 root@v2
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|..   .           |
|... . . . . .    |
|o  .   o . o     |
|.++     S .      |
|*+o+ .   .       |
|#B= +            |
|@OEX +           |
|@=B+B..          |
+----[SHA256]-----+
2、生成的私钥和公钥在/root/.ssh目录下
# v2主机
[root@v2 .ssh]# cd /root/.ssh
[root@v2 .ssh]# ls
id_rsa  id_rsa.pub
3、将v2上的公钥发布到v3上,使得v2可以直接免密登录v3
# 在v2主机上执行
[root@v2 ~]# ssh-copy-id -i /root/.ssh/id_rsa root@192.168.78.103
# 执行返回结果
[root@v2 ~]# ssh-copy-id -i /root/.ssh/id_rsa root@192.168.78.103
/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
root@192.168.78.103's password: 

Number of key(s) added: 1

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

这里我们使用了 ssh-copy-id -i /root/.ssh/id_rsa 指定了私钥,发布到v3上的就是该私钥对应的公钥。

这一步,我们还指定了root@192.168.78.103,也就是说登录192.168.78.103,用其下的root账户登录,因此我们这里也要有其root账户的密码,我们也可以看到命令行里有这么一行root@192.168.78.103's password: ,就是让我们输入192.168.78.103下root账户的密码。

最后提示Number of key(s) added: 1,说明我们已经成功将自己的公钥发布到v3主机上了。

我们在v2主机上将公钥发布到v3主机之后,我们就可以直接使用ssh 192.168.78.103在v2主机免密登录到v3主机了。

同时,我们在v3主机下,会发现在/root目录下生成了一个/root/.ssh/authorized_keys文件,也就是该文件,使得v2主机可以对v3主机免密登录。

# v3主机
[root@v3 ~]# cd /root/.ssh
[root@v3 .ssh]# ls
authorized_keys
[root@v3 .ssh]# 

我们查看该文件,会发现,里面有一段记录就是v2主机上发布过来的公钥。

4、在v2主机免密登录v3
[root@v2 ~]# ssh 192.168.78.103
Last login: Tue Aug 24 09:39:02 2021 from 192.168.78.102
[root@v3 ~]# 

只要执行ssh v3的ip即可