ssh免密登录

示例 A为本地主机,BC为远程服务器

使用ssh-keygen生成密钥对

ssh-keygen

安装ssh-copy-id命令

yum install openssh-clients

拷贝生成的公钥到远程服务器BC,即可在本地主机免密登录远程服务器BC

ssh-copy-id -i ~/.ssh/xxx.pub user@server

示例

[root@ctl01 ~]# ssh-copy-id -i .ssh/id_rsa.pub root@10.191.101.128
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: ".ssh/id_rsa.pub"
The authenticity of host '10.191.101.128 (10.191.101.128)' can't be established.
ECDSA key fingerprint is SHA256:kcGPeZqN7kwKRmmDpg/O3mBazd+psSvHODd8bfUdi6Y.
ECDSA key fingerprint is MD5:e5:b9:be:58:c7:f1:12:bd:66:87:af:94:51:3b:5f:e8.
Are you sure you want to continue connecting (yes/no)? yes
/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@10.191.101.128's password:
 
Number of key(s) added: 1
 
Now try logging into the machine, with:   "ssh 'root@10.191.101.128'"
and check to make sure that only the key(s) you wanted were added.

通俗的理解,在ssh免密登录过程中,“我”生成一对钥匙(私钥)和锁(公钥),将锁分发给其他人,需要时用来锁住必要数据,而只有“我”的钥匙能够打开,以此建立安全连接

ssh互信配置

在三台Linux主机之间配置SSH免密码互信(也称为SSH密钥认证)

步骤1:生成SSH密钥对

在每台主机上生成SSH密钥对,如果尚未生成的话。这通常只需要在第一台主机上执行一次,然后将生成的公钥复制到其他主机。然而,为了确保每台主机都可以无密码登录到其他所有主机,需要在每台主机上都生成一对密钥。

在主机A上执行以下命令:

ssh-keygen -t rsa

按提示操作,可以选择接受默认的文件位置和不设置密码。这将在~/.ssh/目录下生成id_rsa(私钥)和id_rsa.pub(公钥)文件。

步骤2:分发公钥

接下来,将主机A上的公钥复制到其他主机(主机B和C)。可以手动执行,也可以使用ssh-copy-id命令自动完成。

手动方法:

cat ~/.ssh/id_rsa.pub | ssh user@hostB 'cat >> .ssh/authorized_keys'
cat ~/.ssh/id_rsa.pub | ssh user@hostC 'cat >> .ssh/authorized_keys'

使用ssh-copy-id命令:

ssh-copy-id user@hostB
ssh-copy-id user@hostC

步骤3:确保.ssh目录权限正确

确保每台主机上的.ssh目录和authorized_keys文件的权限正确,以防止未授权访问。

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

步骤4:在所有主机上重复步骤1和步骤2

让每台主机都能无密码登录到其他主机,需要在每台主机上重复步骤1和步骤2。也就是说,在主机B和C上也要生成SSH密钥对(如果还没有的话),并将它们的公钥复制到其他主机上。

步骤5:测试免密登录

在完成配置后,从每台主机尝试登录到其他主机,以验证是否成功配置了免密登录。

ssh user@hostB
ssh user@hostC

从主机B和C也进行同样的测试。

注意事项

  • 确保所有主机上的用户名相同,或者在ssh-copy-id命令中使用正确的用户名。
  • 在生成SSH密钥对时,选择不带密码的选项,以便实现免密码登录。
  • 如果你正在配置的主机是新系统,你可能需要创建.ssh目录,并确保它有适当的权限,再进行公钥的复制。