交互式脚本expect场景示例

expect语法示例

#spawn 新建一个进程,这个进程的交互由expect控制
#expect 等待接受进程返回的字符串,直到超时时间,根据规则决定下一步操作
#send 发送字符串给expect控制的进程
#set 设定变量为某个值
#exp_continue 重新执行expect命令分支
#set timeout 30 设置超时时间为30秒,-1不超时,永远等待
#interact 执行完后保持交互状态,如果不加这一项,交互完成会自动退出
#expect eof 等待spawn进程结束后退出信号eof

1.expect实现简单的交互登陆,需要安装expect工具

[root@oldxu shell]# cat expect1.ex
#!/usr/bin/expect
spawn ssh root@172.16.1.7

expect {
	"yes/no" { send "yes
"; exp_continue }
	"password:" { send "123
" };
}
interact

2.expect定义变量实现交互方式

[root@oldxu shell]# cat expect2.ex
#!/usr/bin/expect
set ip 172.16.1.7
set user root
set password 123
set timeout 5

spawn ssh $user@$ip

expect {
    "yes/no" { send "yes
"; exp_continue }
    "password:" { send "$password
" };
}
#交互方式
interact

3.expect进行参数传递,执行命令或其他操作

[root@oldxu shell]# cat expect3.ex
#!/usr/bin/expect
set ip [lindex $argv 0] #接收脚本的第一个位置参数
set user root
set password 123
set timeout 5

spawn ssh $user@$ip

expect {
    "yes/no" { send "yes
"; exp_continue }
    "password:" { send "$password
" };
}

#当出现#号符执行如下命令
expect "#"
send "useradd bgx
"
send "pwd
"
send "exit
"
expect eof

4.批量获取在线主机,进行秘钥批量分发

[root@oldxu shell]# cat expect4.sh
#!/usr/bin/bash

#1.清空下ip.txt文件
> ip.txt

#2.获取存活主机的IP,并写入ip.txt文件中
for i in {7..8}
do
        ip=172.16.1.$i
        {
        ping -c1 -W1 $ip &>/dev/null
        if [ $? -eq 0 ];then
                echo "$ip" >> ip.txt
        fi
        }&
done
	wait &&	echo "IP地址获取成功"

#3.生成对应的密钥
if [ ! -f ~/.ssh/id_rsa ];then
	ssh-keygen -P "" -f ~/.ssh/id_rsa
fi

#4.批量分发密钥
while read line
do
/usr/bin/expect <<-EOF
        set pass 123
        set timeout 2
        spawn ssh-copy-id $line -f
        expect {
		"yes/no" { send "yes
"; exp_continue }
                "password:" { send "$pass
" }
	}
EOF
done<ip.txt
原文地址:https://www.cnblogs.com/xuliangwei/p/11753243.html