码迷,mamicode.com
首页 > 其他好文 > 详细

expect

时间:2020-06-16 15:40:06      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:cal   执行命令   style   opp   lag   信息   echo   需要   字符串   

安装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\n"
expect eof

[root@localhost ~]# expect 1.exp
spawn ssh root@192.168.56.103 ifconfig
root@192.168.56.103s 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\r"; exp_continue }
"*password:" { send "$passwd\r" }
}
expect eof
EOF

 

expect

标签:cal   执行命令   style   opp   lag   信息   echo   需要   字符串   

原文地址:https://www.cnblogs.com/liang545621/p/13140679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!