【问题标题】:Expect: how to spawn a command containing a backslash?期望:如何生成包含反斜杠的命令?
【发布时间】:2017-11-08 23:12:09
【问题描述】:

我有以下脚本:

#!/bin/bash
echo -n "Enter user name: "
read USER
echo -n "Enter password: "
read -s PWD
cat $HOME/etc/switches.txt | while read IP SWITCH
do
  echo ${SWITCH}
  /usr/bin/expect <<EOD
# Change to 1 to Log to STDOUT
log_user 1
# Change to 1 to enable verbose debugging
exp_internal 1
# Set timeout for the script
set timeout 20
spawn ssh -l {$USER} -oCheckHostIP=no -oStrictHostKeyChecking=no -q $IP
match_max [expr 32 * 1024]
expect "Password:"
send $PWD
send "\n"
expect "#"
send "show fcip summary | grep TRNK\n"
EOD
  echo
done

当我运行它时,用户名中的反斜杠消失了,结果如下:

Enter user name: corp\user
Enter password:
=== ss3303-m-esannw-m01a ===
spawn ssh -l corpuser -oCheckHostIP=no -oStrictHostKeyChecking=no -q 10.247.184.70
[...]

我怀疑我的问题部分是由于将我的期望脚本嵌入到 bash 脚本中。我也尝试过使用 $USER 和 "$USER",结果相同。使用 corp\\\\user (是的,四个反斜杠!)确实有效,但不方便。我正在认真考虑使用 sed 或其他东西来增加反斜杠,但很想听听其他想法。

【问题讨论】:

标签: bash expect


【解决方案1】:

通过环境传递变量可能会更好,因此 expect 可以直接访问它们,而不是依赖 shell 将值替换到 heredoc 中:

#!/bin/bash
read -p "Enter user name: " USER
read -sp "Enter password: " PWD
export USER PWD IP
while read IP SWITCH
do
    echo ${SWITCH}
    # the heredoc is single quoted below
    /usr/bin/expect <<'EOD'
        # Change to 1 to Log to STDOUT
        log_user 1
        # Change to 1 to enable verbose debugging
        exp_internal 1
        # Set timeout for the script
        set timeout 20
        match_max [expr {32 * 1024}]

        spawn ssh -l $env(USER) -oCheckHostIP=no -oStrictHostKeyChecking=no -q $env(IP)
        expect "Password:"
        send -- "$env(PWD)\r"
        expect "#"
        send "show fcip summary | grep TRNK\r"
        expect eof
EOD
    echo
done <$HOME/etc/switches.txt 

注意事项:

  • heredoc 是单引号的:shell 不会尝试插入变量
  • 导出了期望代码中使用的shell变量
  • 使用\r“按回车键”发送命令。
  • 整理了用户名和密码的输入
  • 整理阅读文本文件

【讨论】:

  • 谢谢!现在一切正常。 (好吧,现在我还在读取命令中添加了 -r 标志!)
  • -r 的成功之处
猜你喜欢
  • 2013-07-29
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
  • 2023-03-21
  • 2015-03-26
  • 1970-01-01
相关资源
最近更新 更多