在“期望"中使用条件语句 [英] Using conditional statements inside 'expect'
问题描述
我需要使用 expect 自动登录 TELNET 会话,但我需要处理同一个用户名的多个密码.
I need to automate logging into a TELNET session using expect, but I need to take care of multiple passwords for the same username.
这是我需要创建的流程:
Here's the flow I need to create:
- 打开与 IP 的 TELNET 会话
- 发送用户名
- 发送密码
- 密码错误?再次发送相同的用户名,然后发送不同的密码
- 此时应该已成功登录...
就其价值而言,这是我目前所获得的:
For what it's worth, here's what I've got so far:
#!/usr/bin/expect
spawn telnet 192.168.40.100
expect "login:"
send "spongebob
"
expect "password:"
send "squarepants
"
expect "login incorrect" {
expect "login:"
send "spongebob
"
expect "password:"
send "rhombuspants
"
}
expect "prompt>" {
send_user "success!
"
}
send "blah...blah...blah
"
不用说这行不通,而且看起来也不是很漂亮.从我在 Google 的冒险经历来看,expect 似乎是一种黑暗艺术.在此先感谢任何人的帮助!
Needless to say this doesn't work, and nor does it look very pretty. From my adventures with Google expect seems to be something of a dark-art. Thanks in advance to anyone for assistance in the matter!
推荐答案
不得不推荐Exploring Expect适合所有期望程序员的书 - 无价之宝.
Have to recomment the Exploring Expect book for all expect programmers -- invaluable.
我已经重写了你的代码:(未经测试)
I've rewritten your code: (untested)
proc login {user pass} {
expect "login:"
send "$user
"
expect "password:"
send "$pass
"
}
set username spongebob
set passwords {squarepants rhombuspants}
set index 0
spawn telnet 192.168.40.100
login $username [lindex $passwords $index]
expect {
"login incorrect" {
send_user "failed with $username:[lindex $passwords $index]
"
incr index
if {$index == [llength $passwords]} {
error "ran out of possible passwords"
}
login $username [lindex $passwords $index]
exp_continue
}
"prompt>"
}
send_user "success!
"
# ...
exp_continue
循环回到期望块的开头——就像一个重做"语句.
exp_continue
loops back to the beginning of the expect block -- it's like a "redo" statement.
注意 send_user
以
结尾,而不是
Note that send_user
ends with
not
您不必在提示中转义 >
字符:它不是 Tcl 的特殊字符.
You don't have to escape the >
character in your prompt: it's not special for Tcl.
这篇关于在“期望"中使用条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!