期望:如何生成包含反斜杠的命令?

时间:2017-11-08 14:41:54

标签: bash expect

我有以下脚本:

#!/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
[...]

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

1 个答案:

答案 0 :(得分:1)

你可能更幸运通过环境传递变量,所以期望可以直接访问它们,而不是依靠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“按回车”作为发送命令。
  • 整理了用户名和密码的输入
  • 整理阅读文本文件