简体   繁体   English

期望脚本无法读取变量

[英]Expect script can't read a variable

I have been trying to pass a variable to expect script, this variable contains the password for an ssh command, however when I try to execute the script, I receive a message stating that the variable couldn't be read - no such variable.我一直在尝试将变量传递给期望脚本,该变量包含 ssh 命令的密码,但是当我尝试执行脚本时,我收到一条消息,指出无法读取该变量 - 没有这样的变量。

The variable is declared in the shell script, however expect just can't read it.该变量在 shell 脚本中声明,但是无法读取它。

Here is how the variable is declared:以下是变量的声明方式:

D=`s="$LIST1" printenv s |grep $ip | awk '{print $3}'`

If I export variable D, then it works, but I can't have this variable exported to all child process, does anyone know how can I add this variable to expect without having to export it?如果我导出变量 D,那么它可以工作,但是我不能将此变量导出到所有子进程,有谁知道如何添加这个变量来期望而不必导出它?

/usr/bin/expect <<'END_EXPECT'
set timeout -1
log_file  expect-log.txt
spawn -noecho sh ./script.sh
expect "yes" { send "yes\r"}
expect {
    -nocase "*assword*" {
        send "$D\r"
        exp_continue
    }
send \r
    eof
admin@server1's password: can't read "D": no such variable
    while executing
"send "$D\r""
    invoked from within
"expect {
        -nocase "*assword*" {
            send "$D\r"
            exp_continue
        }
    send \r
        eof
    }"

By far the easiest method of getting the variable into expect is by exporting it.到目前为止,将变量放入 expect 的最简单方法是导出它。 You can unexport it after launching expect, and expect can remove the variable from the environment before launching any subprocesses.您可以在启动期望后取消导出它,并且期望可以在启动任何子流程之前从环境中删除变量。

You are strongly advised to not embed the expect script within a shell script, but rather to make it a separate file (that uses Tcl highlighting rules, if you're using an editor that supports it).强烈建议您不要将 expect 脚本嵌入 shell 脚本中,而是将其作为一个单独的文件(如果您使用支持它的编辑器,则使用 Tcl 突出显示规则)。 It's just so much easier that way.这样就容易多了。

# This is bash; other shells have their own quirks
export D=`s="$LIST1" printenv s |grep $ip | awk '{print $3}'`
expect script.expect
unexport D
# Move the variable from the environment to a script variable; DO THIS BEFORE exec OR spawn
set D $env(D)
unset env(D)

set timeout -1
log_file  expect-log.txt
spawn -noecho sh ./script.sh
expect "yes" { send "yes\r"}
expect {
    -nocase "*assword*" {
        send "$D\r"
        exp_continue
    }
send \r
    eof

That code looks incomplete BTW.顺便说一句,该代码看起来不完整。 The braces aren't balanced, the indentation looks strange, and it generally looks like something is missing.大括号不平衡,压痕看起来很奇怪,而且通常看起来好像缺少了什么。 You'll have to fix that before everything works.你必须在一切正常之前解决这个问题。

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

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