shu*_*ter 25 bash automation telnet expect conditional-statements
我需要使用expect自动登录到TELNET会话,但我需要为同一个用户名处理多个密码.
这是我需要创建的流程:
对于它的价值,这是我到目前为止所得到的:
#!/usr/bin/expect
spawn telnet 192.168.40.100
expect "login:"
send "spongebob\r"
expect "password:"
send "squarepants\r"
expect "login incorrect" {
expect "login:"
send "spongebob\r"
expect "password:"
send "rhombuspants\r"
}
expect "prompt\>" {
send_user "success!\r"
}
send "blah...blah...blah\r"
Run Code Online (Sandbox Code Playgroud)
不用说这不起作用,也不是很漂亮.从我与谷歌的冒险预期似乎是暗艺术的东西.在此事先感谢任何人的帮助!
gle*_*man 38
必须为所有期望程序员推荐Exploring Expect书籍 - 非常宝贵.
我重写了你的代码:(未经测试)
proc login {user pass} {
expect "login:"
send "$user\r"
expect "password:"
send "$pass\r"
}
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]\n"
incr index
if {$index == [llength $passwords]} {
error "ran out of possible passwords"
}
login $username [lindex $passwords $index]
exp_continue
}
"prompt>"
}
send_user "success!\n"
# ...
Run Code Online (Sandbox Code Playgroud)
exp_continue 循环回到expect块的开头 - 它就像一个"重做"语句.
注意send_user结束时\n没有\r
您不必>在提示符中转义字符:它对Tcl并不特殊.
shu*_*ter 11
经过一番抨击,我找到了解决方案.事实证明,期望使用我并不熟悉的TCL语法:
#!/usr/bin/expect
set pass(0) "squarepants"
set pass(1) "rhombuspants"
set pass(2) "trapezoidpants"
set count 0
set prompt "> "
spawn telnet 192.168.40.100
expect {
"$prompt" {
send_user "successfully logged in!\r"
}
"password:" {
send "$pass($count)\r"
exp_continue
}
"login incorrect" {
incr count
exp_continue
}
"username:" {
send "spongebob\r"
exp_continue
}
}
send "command1\r"
expect "$prompt"
send "command2\r"
expect "$prompt"
send "exit\r"
expect eof
exit
Run Code Online (Sandbox Code Playgroud)
希望这对其他人有用.
| 归档时间: |
|
| 查看次数: |
63101 次 |
| 最近记录: |