Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

bash - Using conditional statements inside 'expect'

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:

  1. Open TELNET session to an IP
  2. Send user-name
  3. Send password
  4. Wrong password? Send the same user-name again, then a different password
  5. Should have successfully logged-in at this point...

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
"

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 loops back to the beginning of the expect block -- it's like a "redo" statement.

Note that send_user ends with not

You don't have to escape the > character in your prompt: it's not special for Tcl.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...