简体   繁体   English

如何在Expect脚本中使用变量作为期望值(expect -re regex)

[英]How can I use a variable as an expect value in an Expect script (expect -re regex)

I have an expect script where I do not always know the output, nor do I want to hardcode the expected output returned from a given command, instead I pass in a part of the expected output as a command line variable. 我有一个期望脚本,在该脚本中我并不总是知道输出,也不想硬编码从给定命令返回的期望输出,而是将期望输出的一部分作为命令行变量传递。 I then want to use the expected output as part of a regex to validate against. 然后,我想将预期的输出用作正则表达式的一部分进行验证。

I've looked at a few examples and can only see cli vars being used with the send command but not with the expect -re command. 我看了几个示例,只能看到cli vars与send命令一起使用,而没有与Expect -re命令一起使用。

#!/usr/bin/expect

set output [lindex $argv 0]
set host [lindex $argv 1]

set regex "{(?n)^${output}.*}"
puts $regex

set timeout -1

spawn ssh root@$host
expect -re {(?n)^Password.*}

send "myPassword\n"
expect -re $regex

expect eof

OUTPUT 输出值

Password: couldn't compile regular expression pattern: quantifier operand invalid
    while executing
"expect -re $regex"

EXPECTED Regex should be handled as a the value set in the output cli variable. 预期的正则表达式应作为在输出cli变量中设置的值进行处理。

Note well: when values are hardcoded the script works as expected 请注意:对值进行硬编码后,脚本将按预期工作

Braces in a regular expression are quantifier syntax. 正则表达式中的花括号是量词语法。 For example, to find 3 "a", you can use a{3} 例如,要找到3个“ a”,可以使用a{3}

Your assignment of the $regex variable contains literal braces 您对$ regex变量的赋值包含文字括号

set regex "{(?n)^${output}.*}"

expect is an extension of the Tcl language: in Tcl, you use double quotes to enclose a "word" allowing variable and command substitution; Expect是Tcl语言的扩展:在Tcl中,使用双引号将“单词”括起来,以允许变量和命令替换; you use braces to enclose a word with no substititions allowed (like single quotes in the shell). 您使用花括号将一个单词括起来,不允许任何替换(例如外壳中的单引号)。

Simply remove the braces from the $regex value. 只需从$ regex值中删除括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM