[英]How does Expect script determine contents of expect_out
I am trying to write a script will provide credentials to a vpn with one caveat where VPN requires that I provide OTP.我正在尝试编写一个脚本,该脚本将为 vpn 提供凭据,但需要注意的是,VPN 要求我提供 OTP。
This is my script:这是我的脚本:
#! /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
I included an arrow to what I think is the source of the problem because when I run this script, it looks like expect_out contains Password:
.我包含了一个指向我认为问题根源的箭头,因为当我运行这个脚本时,它看起来像 expect_out 包含
Password:
。 Given what i read in man page I imagined that the buffer is cleared each time new match is made and therefore it contains string matched in most recent expect clause( in this case expect_user -re ":(.*)\\r"
), however it seems that I'm wrong.鉴于我在手册页中读到的内容,我想每次进行新匹配时都会清除缓冲区,因此它包含在最近的 expect 子句中匹配的字符串(在这种情况下,
expect_user -re ":(.*)\\r"
),但是看来我错了。 I did not see any notes saying that expect_user contents need to be accessed using different function like interact
does, so I'm not sure where did my password go?我没有看到任何说明需要使用不同的功能访问 expect_user 内容,就像
interact
一样,所以我不确定我的密码去哪里了?
Thank you谢谢
When using send_user
you will not see an echo of what you write, unlike when you send to the spawned command, so you will never match :
unless the user explicitly types it.使用
send_user
您不会看到send_user
内容的回显,这与发送到生成的命令时不同,因此您永远不会匹配:
除非用户明确键入它。 Also, you will read newline, not carriage-return.此外,您将阅读换行符,而不是回车符。 So use
所以用
expect_user -re "(.*)\n"
to get the user input and $expect_out(1,string)
(1 not 0) will contain the input.获取用户输入,
$expect_out(1,string)
(1 not 0) 将包含输入。
What you are observing is a timeout in your expect_user
, which is why the variable is not updated and still contains the old match.您观察到的是您的
expect_user
超时,这就是变量未更新且仍包含旧匹配的原因。
To protect yourself against unseen timeouts, you could set up a "global" timeout check by starting with为了保护自己免受看不见的超时的影响,您可以通过以下方式设置“全局”超时检查
proc abort { } { send_user "Timeout!" ; exit 2 }
expect_before timeout abort
The expect_before
is done "before" each expect
, but also before each expect_user
, it seems. expect_before
是在每个expect
之前expect_user
,而且似乎在每个expect_user
之前expect_user
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.