Shell循环:expect(二)

expect实战:公钥推送

一、准备工作:安装expect,装备公钥

二、通过shell循环判断主机在线

#!/bin/bash    #脚本编写
#创建一个IP地址文件
>ip.txt
#使用for循环ping测试主机是否在线
for i in {3..254}
do
        {
        ip=192.168.151.$i
        ping -c1 -W1 $ip &> /dev/null
        if [ $? -eq 0 ]
        then
                echo "$ip" >> ip.txt
        fi
        }&

done

三、通过expect进行交互

#!/bin/bash
#创建一个IP地址文件
>ip.txt
#使用for循环ping测试主机是否在线
for i in {3..254}
do
        {
        ip=192.168.151.$i
        ping -c1 -W1 $ip &> /dev/null
        if [ $? -eq 0 ]
        then
                echo "$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
EOF
        fi
        }&
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
fi

if [ ! -f /root/.ssh/id_rsa  ]
then
        ssh-keygen -P"" -f ~/.ssh/id_rsa
fi
#使用for循环ping测试主机是否在线之前插入安装和装备公钥。

#创建一个IP地址文件
>ip.txt
#使用for循环ping测试主机是否在线
for i in {3..254}
do
        {
        ip=192.168.151.$i
        ping -c1 -W1 $ip &> /dev/null
        if [ $? -eq 0 ]
        then
                echo "$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
EOF
        fi
        }&
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: 1

Now 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 [email protected]    #脚本测试
Last login: Sun Dec  3 22:31:22 2023 from 192.168.151.158
[root@localhost ~]# ip a | grep inet
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host 
    inet 192.168.151.156/24 brd 192.168.151.255 scope global noprefixroute ens33
    inet6 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 [email protected]
Last login: Sun Dec  3 20:34:45 2023 from 192.168.151.1
[root@localhost ~]# ip a | grep inet
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host 
    inet 192.168.151.157/24 brd 192.168.151.255 scope global noprefixroute ens33
    inet6 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 

Shell循环:expect(二)_第1张图片

Shell循环:expect(二)_第2张图片

你可能感兴趣的:(Shell,linux,bash,shell)