【实验需求】

1、配置三台主机之间基于ssh的key验证,实现Rocky8-mini1和Rocky8-mini2、Rocky8-mini3单向进行远程访问时无需输入密码

【实验环境】

1
2
3
Rocky8-mini1     192.168.119.128
Rocky8-mini2 192.168.119.138
Rocky8-mini3 192.168.119.129

【实验过程】

1、准备主机与密码文件

1
2
3
[root@Rocky8-mini ~]# cat hostlist 
192.168.119.138 wuhaolam
192.168.119.129 wuhaolam

2、准备运行脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/bin/bash

# 需要有hostlist文件
#[root@centos7-server2 ~]# cat hostlist
#192.168.119.146 wh
#192.168.119.150 ww

if [ ! -e /root/.ssh/id_rsa ];then
echo -e "\E[1;32m开始生成密钥对...\E[0m"
ssh-keygen -P "" -f /root/.ssh/id_rsa &> /dev/null
else
echo -e "\E[1;34m密钥对已经存在\E[0m"
fi


if ! rpm -q sshpass &> /dev/null;then
yum -y install sshpass &> /dev/null || { echo -e '\E[1;31m"error: sshpass packet install false!"\E[0m'; exit; }
fi


while read IP PASSWORD; do
sshpass -p $PASSWORD ssh-copy-id -o StrictHostKeyChecking=no $IP &> /dev/null
echo $IP key_authentication already done.
done < hostlist

echo -e "\E[1;32msuccessful\E[0m"

【实验结果】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Rocky8-mini 访问另外两台主机时无需输入密码即可登录成功
[root@Rocky8-mini ~]# ssh 192.168.119.129
Last login: Wed Jul 26 03:33:07 2023 from 192.168.119.128
[root@Rocky8-mini3 ~]# exit
logout
Connection to 192.168.119.129 closed.
[root@Rocky8-mini ~]# ssh 192.168.119.138
Last login: Wed Jul 26 15:32:26 2023 from 192.168.119.128
[root@Rocky8-mini2 ~]# exit
logout
Connection to 192.168.119.138 closed.

# Rocky8-mini2 和 Rocky8-mini3 之间无法直接登录
[root@Rocky8-mini2 ~]# ssh root@192.168.119.129
root@192.168.119.129's password:

# Rocky8-mini2 和 Rocky8-mini3 无法免密码直接登录 Rocky8-mini
[root@Rocky8-mini3 ~]# ssh root@192.168.119.128
root@192.168.119.128's password: