无法通过ssh

时间:2016-04-12 21:13:54

标签: bash ssh

我编写了一个deployAll.sh,它逐行读取ip_host.list,然后为所有远程主机添加组,

当我运行时:sh deployAll.sh

结果:

Group is added to 172.25.30.11

不是预期的结果:

Group is added to 172.25.30.11
Group is added to 172.25.30.12  
Group is added to 172.25.30.13

为什么它只执行第一个?请帮助,非常感谢!

deployAll.sh

    #!/bin/bash

    function deployAll()
    {
        while read line;do
            IFS=';' read -ra ipandhost<<< "$line"
            ssh "${ipandhost[0]}" "groupadd -g 1011 test"
            printf "Group is added to ${ipandhost[0]}\n"
        done < ip_host.list
    }

deployAll

ip_host.list

172.25.30.11;test-30-11
172.25.30.12;test-30-12
172.25.30.13;test-30-13

3 个答案:

答案 0 :(得分:3)

这是一个常见的问题,这是由ssh的特殊行为造成的,它会淹没 stdin ,使循环挨饿(即while read line;do ...;done

请参阅详细讨论此主题的Bash FAQ 89

在这种情况下,我也回答(并解决了)与ffmpeg类似的问题,其行为与ssh相同。这里:When reading a file line by line, I only get to execute ffmpeg on the first line

TL; DR:

主要有三种选择:

  • 使用ssh的{​​{1}}选项。引自-n
man ssh
  • -n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The ssh pro‐ gram will be put in the background. (This does not work if ssh needs to ask for a password or passphrase; see also the -f option.) 行(即</dev/null)末尾添加ssh将解决问题,并使ssh ... </dev/null按预期行事。< / p>

  • sshFile Descriptor读取一个随机程序不太可能使用的内容:

    read

答案 1 :(得分:1)

没有ssh命令(在我的网络上没有意义),我得到预期的输出,所以我怀疑ssh命令正在吞下剩余的标准输入。您应该使用-n标记阻止sshstdin读取(相当于从stdin重定向/dev/null):

ssh -n "${ipandhost[0]}" "groupadd -g 1011 test"

ssh "${ipandhost[0]}" "groupadd -g 1011 test" < /dev/null

另见How to keep script from swallowing all of stdin?

答案 2 :(得分:0)

我的解决方案是通过ssh-keygen命令生成ssh密钥,并替换现有的公共密钥文件(如果有)。之后安装将恢复。