expect

安装expect
yum install -y expect


expect常用命令总结:
spawn 交互程序开始后面跟命令或者指定程序
expect 获取匹配信息匹配成功则执行expect后面的程序动作
send exp_send 用于发送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用来打印输出 相当于shell中的echo
exit 退出expect脚本
eof expect执行结束 退出
set 定义变量
puts 输出变量
set timeout 设置超时时间


范例一:ssh登录远程主机执行命令,执行方法 expect 1.sh 或者 ./1.sh
[root@localhost ~]# cat 1.exp
#!/usr/bin/expect
spawn ssh root@192.168.56.103 ifconfig
expect "*password"
send "123456
"
expect eof

[root@localhost ~]# expect 1.exp
spawn ssh root@192.168.56.103 ifconfig
root@192.168.56.103's password: 
ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.56.103 netmask 255.255.255.0 broadcast 192.168.56.255
inet6 fe80::9e0a:2fa8:e595:9c94 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:dc:16:df txqueuelen 1000 (Ethernet)
RX packets 4876290 bytes 443505840 (422.9 MiB)
RX errors 0 dropped 449 overruns 0 frame 0
TX packets 4610706 bytes 10191880682 (9.4 GiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 38696 bytes 2957553 (2.8 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 38696 bytes 2957553 (2.8 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

 


范例二:ssh远程登录主机执行命令,在shell脚本中执行expect命令,执行方法sh 2.sh、bash 2.sh 或./2.sh都可以执行.

#!/bin/bash

passwd='123456'

/usr/bin/expect <<-EOF

set time 30
spawn ssh saneri@192.168.56.103 df -Th
expect {
"*yes/no" { send "yes
"; exp_continue }
"*password:" { send "$passwd
" }
}
expect eof
EOF
原文地址:https://www.cnblogs.com/l10n/p/13140679.html