Using conditional statements inside 'expect'

前端 未结 3 970
感情败类
感情败类 2020-12-01 05:27

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

3条回答
  •  猫巷女王i
    2020-12-01 06:03

    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\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"
    # ...
    

    exp_continue loops back to the beginning of the expect block -- it's like a "redo" statement.

    Note that send_user ends with \n not \r

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

提交回复
热议问题