【问题标题】:How can I pass a shell script variable into an Expect script?如何将 shell 脚本变量传递给 Expect 脚本?
【发布时间】:2014-02-21 07:40:37
【问题描述】:

我想将 $SPACE 变量传递给 Expect 脚本并获取输出,然后再次传递给 shell 脚本。

#!/bin/bash -x

    SPACE=$(df -h | awk '{ print $5 }' | grep -v Use |sort -n |tail -1 | cut -d % -f1)
    #set user "root"
    #set ip "192\.168\.53\.197"
    #echo $SPACE

    expect<<EOF

    spawn ssh "root\@192\.168\.53\.197"

    expect "Password:"

    send "Karvy123$\r";

    expect "prompt"

    send "$SPACE\r";

    expect "prompt"

    EOF

【问题讨论】:

  • 有效吗?如果没有,你会得到什么错误?
  • 我得到错误 [root@localhost ~]# 47 -bash: 47: command not found
  • 47 来自哪里?
  • 我认为价值来自$SPACE
  • 另外,请注意结尾的“EOF”不能有前导空格:您在此处粘贴的 shell 脚本将不起作用。

标签: shell expect


【解决方案1】:

哦,我明白了。您希望 $SPACE 保存命令,而不是值。此构造将执行命令并将输出保存在变量中:x=$(cmd arg arg)。因此,您正在查找本地主机上使用的空间并将该值发送到远程主机。

你需要这样的东西:

#!/bin/bash
export cmd="df -h | awk '{ print \$5 }' | grep -v Use |sort -n |tail -1 | cut -d % -f1"
remote_usage=$(
    expect <<'EOF'
    log_user 0
    spawn -noecho ssh "root@192.168.53.197"
    expect "Password:"
    send "*****\r"
    expect "prompt"
    send "$env(cmd)\r"
    expect -re {(?n)^(\d+)$.*prompt}
    send_user "$expect_out(1,string)\n"
    send "exit\r"
    expect eof
EOF
)
echo "disk usage on remote host: $remote_usage"

但是,您不必执行任何操作。设置 SSH 密钥(使用 ssh-keygenssh-copy-id)并执行

remote_usage=$( ssh root@192.168.53.197 sh -c "df -h | awk '{ print \$5 }' | grep -v Use |sort -n |tail -1 | cut -d % -f1" )

【讨论】:

  • 感谢您的回复...@glenn 我收到以下错误--> 无法读取 "expect_out(buffer)": no such variable while execution "send_user "$expect_out(buffer) \n""
  • #!/bin/bash export cmd="df -h | awk '{ print \$5 }' | grep -v 使用 |sort -n |tail -1 | cut -d % -f1 " remote_usage=$( 期望
  • 使用expect_out(1,string)而不是expect_out(buffer)——前者只是命令输出的数字;后者将包括命令、提示等
  • 我使用的代码与您在出现相同错误后提供的代码相同---> 无法读取 "expect_out(1,string)": no such variable while execution "send_user "$expect_out(1 ,string)\n""