如何在前台循环交互式SSH连接?

时间:2012-06-09 14:30:03

标签: bash ssh

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

这是我的剧本:

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号出口)处为contintue。 我尝试了命令“等待”或后台作业和“fg%1”,但没有任何效果。

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

2 个答案:

答案 0 :(得分: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重定向可能存在的问题

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

# 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"

答案 1 :(得分:2)

当ssh在带有stdin重定向的while循环中运行时,它似乎会挂起。请尝试以下方法之一:

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

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

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

顺便说一下,您可以cut直接使用read代替while IFS== read -r user ip

exit 1

你为什么要做{{1}}?非零表示失败。

相关问题