gpt4 book ai didi

bash - ssh无法在多个远程主机中运行脚本

转载 作者:行者123 更新时间:2023-12-02 14:12:14 25 4
gpt4 key购买 nike

我编写了一个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

最佳答案

这是一个常见的问题,是由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-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)将解决此问题,并使ssh发挥预期的作用。
  • readFile Descriptor中读取,这不太可能被随机程序使用:
       while IFS= read -r line <&3; do
    # Here read is reading from FD 3, to which 'ip_host.list' is redirected.
    done 3<ip_host.list
  • 关于bash - ssh无法在多个远程主机中运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36584158/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com