使用内部条件语句'希望' [英] Using conditional statements inside 'expect'

查看:188
本文介绍了使用内部条件语句'希望'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用自动登录到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.

这是我需要创建流程:


  1. 开启Telnet会话的IP

  2. 发送用户名

  3. 发送密码

  4. 密码错误?再次发送相同的用户名,然后不同的密码

  5. 如果成功登录,在这一点上...

有关它的价值,这是我到目前为止有:

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

不用说,这是不行的,而且也不会显得很pretty。从我的冒险与谷歌的希望似乎是一个暗艺术。在此先感谢任何人在这个问题上的援助!

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!

推荐答案

不得不电子书籍的探索期待书都期望程序员 - 无价

Have to recomment the Exploring Expect book for all expect programmers -- invaluable.

我已经重写你的code:(未经测试)

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 循环回的预期开始块 - 它就像一个重做语句

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

注意 send_user \\ n结束不是 \\ r

您不必逃避> 字符提示符:这不是专门对Tcl

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

这篇关于使用内部条件语句'希望'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆