expect 在Linux环境下,经常使用shell脚本提高效率,而劲量减少手动输入命令 但是,有些操作是交互式的,只有等待shell返回特定的值,才能执行下一命令 此时我们就要用到expect,来提
expect
在Linux环境下,经常使用shell脚本提高效率,而劲量减少手动输入命令
但是,有些操作是交互式的,只有等待shell返回特定的值,才能执行下一命令
此时我们就要用到expect,来提前设置好与shell的对话内容,从而实现自动化交互式
spawn # starts a process
-expect # wait for strings for a process
-send # send strings to a process
interact # turn control from script over to user
set # 设置一些变量,最常用yu设置timeout
exp_continue # 使用类似shell的case模式时,返回继续判断匹配
expect eof #
expect和send一般成对出现,出现一或多次
#!/usr/bin/expect -d #debug模式
-c # shell脚本中使用expect?
-f
-i
--
-D
[root@localhost ~]# expect -c 'expect "ping" {send "pang/n"}'ping #输入ping回车pang
#!/bin/bashset timeout 5expect -c'spawn ssh [email protected] "whoami;echo hello;pwd;"expect { "yes/no" {send "yes/r";exp_continue} "password" {send "123456/r";} "No route" exit "Connection refused" exit}expect eofexit'# 这种形式 -c'' 中无法使用变量
#免手动输入密码远程登录#!/usr/bin/expectset timeout 5spawn ssh [email protected] { #注意{前面有一空格 "yes/no" {send "yes/n";exp_continue} # exp_continue,进行下一次expect "password" {send "123456/n";} "No route" exit "Connection refused" exit}interact #保留shell控制权
#远程执行命令后退出#!/usr/bin/expect#file_name: expect03if {$argc != 2} { puts "usage: ./expect03 <user@host> <msg>" exit 40}set timeout 5set pw "123456"set host [lindex $argv 0] #参数set msg [lindex $argv 1]spawn ssh $hostexpect { "yes/no" {send "yes/r";exp_continue} "password" {send "$pw/r";} "No route" exit "Connection refused" exit}expect -re "/](/$|#)" #正则send "whoami;echo $msg;pwd/r"expect eofexit./expect03 [email protected] ship #使用参数,让程序更通用# [lindex $argv 0]与shell脚本的$0不同,却等于$1# expect设置了argc、argv0、argv三个变量;argc为参数数量,argv0等于$0,所有的参数放到argv# 详细参见 #!/usr/bin/expect -d 的调试过程
expect " " #模式一send " "expect " " {send " "} #模式二expect { #模式三 " " {send " ";exp_continue} " " {send " ";} " " exit}
http://blog.csdn.net/leexide/article/details/17485451 Shell脚本学习之expect命令
https://book.douban.com/subject/1757462/ Exploring Expect
http://xstarcd.github.io/wiki/shell/expect.html expect - 自动交互脚本
https://www.centos.bz/2013/07/manager-multiple-servers-with-expect/