我的代码:
spawn telnet $ip
expect "Password: "
exp_send "$paswd\r"
expect "Router>"
exp_send "en\r"
expect "Password: "
exp_send "$paswd\r"
expect "Router#"
exp_send "\r"
expect "Router#"
exp_send "\r"
expect "Router#"
exp_send "\r"
expect "Router#"
exp_send "\r"
expect "Router#"
exp_send "conf t\r"
expect "Router(config)#"
exp_send "\r"
expect "Router(config)#"
exp_send "ip ftp username name\r"
expect "Router(config)#"
exp_send "ip ftp password name123\r"
expect "Router(config)#"
exp_send "end"
expect "Router#"
exp_send "\r"
expect "Router#"
exp_send "\r"
expect "Router#"
exp_send "\r"
expect "Router#"
exp_send "copy ftp: filename\r"
expect "Address or name of remote host []? "
exp_send "$remote_ip\r"
expect "Source filename []? "
exp_send "router-config1\r"
expect "Destination filename []? "
exp_send "/new/location\r"
expect "Router#"
输出:
Router(config)#ip ftp username name
Router(config)#ip ftp password name123
Router(config)#endTcpping succeeded for port 443.
Tcpping succeeded for port 443.
Router#
Router#
Router#copy ftp: filename
Address or name of remote host []? Tcpping succeeded for port 443.
Tcpping succeeded for port 443.
$remote_ip
Source filename []? Tcpping succeeded for port 443.
Tcpping succeeded for port 443.
filename
Destination filename [filename]? Tcpping succeeded for port 443.
Tcpping succeeded for port 443.
/new/location
%Warning:There is a file already existing with this name
Do you want to over write? [confirm]Tcpping succeeded for port 443.
Tcpping succeeded for port 443.
Accessing ftp://$remote_ip//filename...
%Error opening ftp://$remote_ip//router-config (No such file or directory)
Router#copy t1_working startup-config
Destination filename [startup-config]? Tcpping succeeded for port 443.
有人可以告诉我如何捕获NO SUCH FILENAME的异常吗?
答案 0 :(得分:1)
您可以让Expect一次等待两个(或更多)不同的字符串。
expect {
"Thing for success" {
# little script to handle the success case
puts "hooray, going to do next step"
}
"Thing for failure 1" {
puts "oh dear; didn't work"
exit 1
}
"Thing for failure 2" {
send "something to try to recover\r"
exp_continue; # Try this expect again
}
}
当然,你需要选择适当的东西来匹配(检查使用glob或正则表达式匹配),你需要弄清楚如何实际处理错误情况(你的选择通常是变化的“忽略”,“失败”和“试图恢复”)。还要考虑明确处理超时。