#expect实现自动交互#
在写脚本的过程中可能会遇到一些需要人机交互的命令,这令自动化带来了不便。使用expect可解决这个问题。省去各种复杂的参数,expect可简单的用如下方式进行使用,其中cmd是个命令字符串。
expect -c cmd
expect也可以写成脚本,通过以下例子来对常用易用的命令进行说明。expect用的是tcl((Tool Command Language)语法,其中常用的命令有spawn, send, expect, and interact,以下面的例子进行说明。下面的例子实现了用ssh对远程主机进行操作.
#!/usr/bin/expect
set timeout 30
set user [lindex $argv 0]
set ip [lindex $argv 1]
set pwd [lindex $argv 2]
set cmd [lindex $argv 3]
if {$cmd == ""} {
set cmd exit
}
spawn -noecho ssh ${user}@${ip} ${cmd}
expect {
(yes/no)? {
send "yes\r"
exp_continue
} Password: {
stty -echo
send ${pwd}\r
stty echo
} timeout: {
send_user "time out\n"
exit
} eof {
#exit $expect_out(1, string)
}
}
interact