【问题标题】:How does Expect script determine contents of expect_outExpect脚本如何确定expect_out的内容
【发布时间】:2020-07-14 16:41:30
【问题描述】:

我正在尝试编写一个脚本,它将向 vpn 提供凭据,但需要注意的是,VPN 要求我提供 OTP。

这是我的脚本:

#! /usr/bin/expect

set vpn    [ lindex $argv 0]
set group  [ lindex $argv 1]
set user   [ lindex $argv 2]
set secret [ lindex $argv 3]

log_user 2 
spawn nmcli con up $vpn --ask

expect {
        "GROUP:" { 
                send "$group\r"
                exp_continue
        }
        "Username:" { 
                send "$user\r"
                exp_continue
        }
        Password: {
                send_user "\nProvide RSA OTP:"
                expect_user -re ":(.*)\r"
                set otp $expect_out(0,string)  <--------- Error!!!
                set pass "$secret$otp"
                send "$pass\r"
                exp_continue
        }
        "Connection successfully activated" {
                send_user "Connected to VPN\r"
        }
        "Login failed" {
                send_user "Login failed\r"
                exp_continue
        }
        "already active" {
                send_user "Already connected to VPN\r"
        }
}
exit

我在我认为是问题根源的地方添加了一个箭头,因为当我运行这个脚本时,它看起来像 expect_out 包含 Password:。鉴于我在手册页中读到的内容,我想象每次进行新匹配时都会清除缓冲区,因此它包含在最近的期望子句中匹配的字符串(在本例中为 expect_user -re ":(.*)\r"),但似乎我错了。我没有看到任何说明需要使用 interact 等不同功能访问 expect_user 内容的注释,所以我不确定我的密码去哪儿了?

谢谢

【问题讨论】:

  • 你不想使用 1 来获取捕获组,而不是 0 来获取整个匹配吗?
  • 模式中的\r 看起来也不正确。请参阅手册页中的示例。
  • 提示:使用parray 命令检查 Tcl 数组的内容:parray expect_out

标签: bash automation expect


【解决方案1】:

使用send_user 时,您不会看到您所写内容的回显,这与发送到衍生命令时不同,因此您永远不会匹配:,除非用户明确键入它。此外,您将阅读换行符,而不是回车符。所以使用

expect_user -re "(.*)\n"

获取用户输入,$expect_out(1,string) (1 not 0) 将包含输入。

您观察到的是 expect_user 中的超时,这就是变量未更新且仍包含旧匹配项的原因。


为了保护自己免受看不见的超时,您可以设置一个“全局”超时检查,从

开始
proc abort { } { send_user "Timeout!" ; exit 2 }
expect_before timeout abort

expect_before 似乎在每个 expect“之前”完成,但似乎也在每个 expect_user 之前完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多