在期望脚本中循环

时间:2014-12-12 19:01:01

标签: networking tcl expect system-administration

我是新手,希望编写脚本,我想写下这样的内容:

set variable;
$variable = expect -exact "\/----Enter Password----\\"
while { != $variable } {
send -- {^[-}
}

我想继续发送转义+连字符,直到我期待这个提示:" / ----输入密码---- \"。我已经写了上面的代码,但它没有用。我该怎么做,请帮助我。

1 个答案:

答案 0 :(得分:3)

您可以使用exp_continue来处理这种情况。命令exp_continue允许期望自己继续执行而不是像通常那样返回。这对于避免显式循环或重复期望语句很有用。默认情况下,exp_continue会重置timeout计时器。如果使用exp_continue标志调用-continue_timer,则不会重新启动计时器。

expect中,默认超时为10秒。即expect等待预期字符串出现的时间。

我们曾经在expect中给出了预期的字符串,如

expect "name"

将等待字符串' name'如果超时发生,则继续下一个语句。要处理超时方案,我们在timeout本身使用关键字expect

expect {
       "name" { # Some code here }
        timeout { # timeout_hanlder_code_here }
}

您可以使用timeout命令更改set值,如下所示。

set timeout 60; # Timeout will happen after 60 seconds.

所以,将所有内容合并在一起,

expect { 
        # If the phrase 'Enter Password' seen, then it will send the password
        "Enter Password" {send "yourpassword\r"}
        # If 'timeout' happened, then it will send some keys &
        # 'expect' will be looped again. 
        timeout {send -- {^[-}; exp_continue}
}

注意:我发现您的代码存在问题。您已经提到必须将escape +连字符键一起发送。但是,您只发送文字方括号([)和连字符(-)符号。如果它工作那么好,你不需要阅读这个'注意' section.Skip它。否则,请继续阅读以下内容。

您应该将实际的转义字符发送到该程序。它可以作为

完成
send -- \033-; # Sending Escape + hyphen together

这是\033是什么?它是Escape键的八进制代码。然后,我们只是将连字符与它的符号组合为-,结果为\033-。所以我们的最终代码将是,

expect { 
            # If the phrase 'Enter Password' seen, then it will send the password
            "Enter Password" {send "yourpassword\r"}
            # If 'timeout' happened, then it will send some keys &
            # 'expect' will be looped again. 
            timeout {send -- \033-; exp_continue}
    }

参考:Tcl's wiki& ASCII Char Table

相关问题