expect实战:公钥推送
一、准备工作:安装expect,装备公钥
二、通过shell循环判断主机在线
#!/bin/bash #脚本编写
#创建一个IP地址文件
>ip.txt
#使用for循环ping测试主机是否在线
for i in {3..254}
do{ip=192.168.151.$iping -c1 -W1 $ip &> /dev/nullif [ $? -eq 0 ]thenecho "$ip" >> ip.txtfi}&done
三、通过expect进行交互
#!/bin/bash
#创建一个IP地址文件
>ip.txt
#使用for循环ping测试主机是否在线
for i in {3..254}
do{ip=192.168.151.$iping -c1 -W1 $ip &> /dev/nullif [ $? -eq 0 ]thenecho "$ip" >> ip.txt/usr/bin/expect <<-EOF
set timeout 10
spawn ssh-copy-id $ip
expect{
"yes/no"{ send "yes\r";exp_continue }
"password:"{ send "666666\r" }
}
expect eof
EOFfi}&
done
wait
echo "公钥推送成功。"
三、优化脚本
#!/bin/bash
#检测expect是否安装,检测公钥是否创建
rpm -q expect &> /dev/null
if [ $? -ne 0 ]
then
yum install -y expect.x86_64 tcl tclx tcl-devl
fiif [ ! -f /root/.ssh/id_rsa ]
thenssh-keygen -P"" -f ~/.ssh/id_rsa
fi
#使用for循环ping测试主机是否在线之前插入安装和装备公钥。#创建一个IP地址文件
>ip.txt
#使用for循环ping测试主机是否在线
for i in {3..254}
do{ip=192.168.151.$iping -c1 -W1 $ip &> /dev/nullif [ $? -eq 0 ]thenecho "$ip" >> ip.txt/usr/bin/expect <<-EOF
set timeout 10
spawn ssh-copy-id $ip
expect{
"yes/no"{ send "yes\r";exp_continue }
"password:"{ send "666666\r" }
}
expect eof
EOFfi}&
done
wait
echo "公钥推送成功。"
四、脚本测试
[root@localhost ~]# bash exp2.sh #脚本执行
spawn ssh-copy-id 192.168.151.158
spawn ssh-copy-id 192.168.151.156
spawn ssh-copy-id 192.168.151.157
......
Number of key(s) added: 1Now try logging into the machine, with: "ssh '192.168.151.158'"
and check to make sure that only the key(s) you wanted were added.公钥推送成功。[root@localhost ~]# ssh root@192.168.151.156 #脚本测试
Last login: Sun Dec 3 22:31:22 2023 from 192.168.151.158
[root@localhost ~]# ip a | grep inetinet 127.0.0.1/8 scope host loinet6 ::1/128 scope host inet 192.168.151.156/24 brd 192.168.151.255 scope global noprefixroute ens33inet6 fe80::51ab:353a:cb8b:b179/64 scope link tentative noprefixroute dadfailed inet6 fe80::c512:a11a:c08e:7391/64 scope link noprefixroute
[root@localhost ~]# exit
登出
Connection to 192.168.151.156 closed.
[root@localhost ~]# ssh root@192.168.151.157
Last login: Sun Dec 3 20:34:45 2023 from 192.168.151.1
[root@localhost ~]# ip a | grep inetinet 127.0.0.1/8 scope host loinet6 ::1/128 scope host inet 192.168.151.157/24 brd 192.168.151.255 scope global noprefixroute ens33inet6 fe80::c512:a11a:c08e:7391/64 scope link tentative noprefixroute dadfailed inet6 fe80::51ab:353a:cb8b:b179/64 scope link tentative noprefixroute dadfailed inet6 fe80::8dbb:75c2:720f:ede9/64 scope link noprefixroute