我有一个expect
脚本包装在一个bash脚本中,用于执行特定命令,具体取决于是否从Cisco路由器中提取IP地址。我正在尝试编码的算法类似于以下内容:
send -h "ip int br"
expect -re {
if "192\.[0-9]{1,3}\.{2}[0-9]{1,3}"
{
expect
{
"up/up { do these things here }
"down/down" { do this instead }
}
}
else
{
send -h "<another command>"
expect
{
"up/up" { do this }
"down/down" { or this if down }
}
}
}
我该怎么做?我已经尝试使用expect
等同于switch
语句和-ex
标记,如对另一个用户的问题(Making decisions on expect return)的回答中所建议但是没有结果。
有什么想法吗?
答案 0 :(得分:1)
我会捕获返回的地址然后对其采取行动。我看到重复的代码,所以尽量减少:
send -h "ip int br"
expect {
timeout {error "can't find an ip address after 'ip int br' command"}
-re {\m\d{1,3}(\.\d{1,3}){3}\M}
}
if { ! [regexp {192\.[0-9]{1,3}\.{2}[0-9]{1,3}} $expect_out(0,string)]} {
send -h "<another command>"
}
expect {
"up/up" { do these things here }
"down/down" { do this instead }
}
其他说明:
"192\.[0-9]{1,3}\.{2}[0-9]{1,3}"
会给你一个类似invalid command name "0-9"
的错误 - 括号对于Tcl是特殊的,除非它们在括号内,否则需要进行转义。