代码之家  ›  专栏  ›  技术社区  ›  samwyse

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

  •  0
  • samwyse  · 技术社区  · 8 年前

    我有以下脚本:

    #!/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脚本中嵌入了expect脚本。我也尝试过使用$USER和“$USER”,结果是一样的。使用corp\\\\user(是的,四个反斜杠!)确实有效,但不方便。我正在认真考虑使用sed或其他方法来增加反斜杠,但我很想听听其他的想法。

    1 回复  |  直到 8 年前
        1
  •  1
  •   glenn jackman    8 年前

    您可能会更幸运地通过环境传递变量,以便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是单引号:外壳不会尝试插入变量
    • 导出了expect代码中使用的shell变量
    • 使用 \r
    • 整理用户名和密码的输入
    • 整理阅读文本文件