Linux简单交互expect

expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。

expect需要下载才能使用;

yum -y install expect

expect自动交互流程:

  spawn启动指定进程---expect获取指定关键字---send向指定程序发送指定字符---执行完成退出.

示例脚本:获取某段地址内在线ip,并收集;最后expect交互发送公钥免密;

[root@k8s-master ~]# cat get_ip_ssh.sh
#!/bin/bash
>/root/ip.txt
password=root
user=root

#判断expect包并下载
rpm -q expect &> /dev/null
if [ $? -ne 0 ] ; then
        yum -y install expect &> /dev/null
        if [ $? -ne 0 ] ; then
                echo "expect is not existent and yum failed"
        fi
fi

#判断密钥文件是否存在
if [ ! -f ~/.ssh/id_rsa ] ; then
        ssh-keygen -P "" -f ~/.ssh/id_rsa &> /dev/null
fi

#收集ip并免密
for i in {200..205}
do
        {
        ip=192.168.75.$i
        ping -c1 -W1 $ip &>/dev/null
        if [ $? -eq 0 ];then
                echo "$ip" >> /root/ip.txt
                /usr/bin/expect <<-EOF
                spawn ssh-copy-id $user@$ip
                expect {
                        "yes/no" { send "yes\r"; exp_continue }
                        "password:" { send "$password\r" }
                }
                expect eof
                EOF
        fi
        }&
done
[root@k8s-master ~]#
posted @ 2021-09-24 11:20  du-z  阅读(76)  评论(0编辑  收藏  举报