【问题标题】:How can I loop through interactive SSH connections in the foreground?如何在前台循环访问交互式 SSH 连接?
【发布时间】:2012-06-09 14:30:02
【问题描述】:

我正在尝试在 bash 脚本中通过 SSH 进行连接。

这是我的脚本:

file_table="${HOME}/.scripts/list.txt"

    while read line; do  
  user=$(echo $line | cut -d\= -f1)

  if [ "$1" = "$user" ]; then
        ip=$(echo $line | cut -d\= -f2)
        ssh -t -t -X "$ip"  
  fi
done < $file_table

exit 1

我在 list.txt 中保存了一些别名,例如: “name1=192.168.1.1”、“name2=127.0.0.1”等等。

问题:SSH 连接没有等待。它只是询问密码,如果建立连接,它会在脚本处继续(退出 1)。 我尝试了命令“等待”或后台作业和“fg %1”,但没有任何效果。

注意:我不想在连接建立后执行命令。在我退出之前我不会保持连接。

【问题讨论】:

    标签: bash ssh


    【解决方案1】:

    当 ssh 在 while 循环中运行并重定向 stdin 时,它可能会出现挂起。尝试以下方法之一:

    ssh -t -t -n -X "$ip"
    

    ssh -t -t -X "$ip" </dev/null
    

    ssh -t -t -f -X "$ip"
    

    顺便说一句,您可以将read 直接放入您的变量中,而不是使用cut

    while IFS== read -r user ip
    

    你为什么要exit 1?非零表示失败。

    【讨论】:

    • “当 ssh 在 while 循环中运行并重定向标准输入时,它可能会出现挂起。”
    【解决方案2】:

    SSH 可能出现的问题

    也许您有一个别名或函数将 SSH 发送到后台,或者您的 SSH 配置文件中发生了其他事情。我用一个显式关闭别名的简化循环进行了测试,它在 shell 提示符下对我来说很好:

    # Loop without the other stuff.
    while true; do
        command ssh -o ControlPersist=no -o ControlPath=none localhost
    done
    

    您可以随时尝试set -x 来查看 Bash 对您的命令行做了什么,并尝试ssh -v 来获得更详细的输出。

    Shell 重定向可能出现的问题

    在考虑了一个替代答案后,我同意另一个相关问题是标准输入的重定向。这对我有用,即使标准输入重定向到循环中:

    # Generic example of bullet-proofing the redirection of stdin.
    TTY=$(tty)
    while true; do
        ssh  -o ControlPersist=no -o ControlPath=none localhost < $TTY
    done < /dev/null
    

    考虑到这一点,您的原始循环可以被清理并重写为:

    TTY=$(tty)    
    while IFS== read -r user ip; do
        [[ "$user" == "$1" ]] && ssh -ttX "$user@$ip" < $TTY
    done < "${HOME}/.scripts/list.txt"
    

    【讨论】:

    • 没有别名,我没有更改 SSH 配置中的任何内容。对于您的代码示例,这是相同的行为。使用 -x 和 -v 我看不到任何特别之处。
    猜你喜欢
    • 2017-02-16
    • 2014-11-30
    • 2022-01-26
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    相关资源
    最近更新 更多