【问题标题】:Linux bash nohup + background in a for loop hang [duplicate]Linux bash nohup + for循环中的背景挂起[重复]
【发布时间】:2015-11-16 16:10:33
【问题描述】:

早安!尝试使用 nohup 在多个服务器上启动脚本并使其在后台运行。

命令(由我的供应商提供)在每个服务器上直接输入时按预期运行(python 脚本会抓取日志文件并通过 UDP 将相关信息发送到另一台服务器):

  nohup tail -f /log/log.log | python /test/deliver.py > /dev/null 2>&1 & 

但是,当进入 for 循环以到达许多服务器时,我必须在每个服务器之间按 Ctrl-C 以保持循环继续。

如果可能,请提供帮助:

for i in `cat /etc/hosts`; do ssh $i nohup tail -f /log/log.log | python /test/deliver.py > /dev/null 2>&1 &; done 

解决方案(谢谢大家的帮助):

ssh -f user@host "cd /whereever; nohup ./whatever > /dev/null 2>&1 &"

必须将 -f 与双引号结合使用,如下所述:

Getting ssh to execute a command in the background on target machine

【问题讨论】:

  • 您正在本地运行 nohup tail -f /log/log.logssh| python ... 管道下。命令解析。单引号你想在远程主机上运行的整个命令。
  • 感谢您的快速响应 Etan - 尝试了以下,相同的结果 - 脚本成功启动,但 ssh 会话挂起等待 ctrl-C 恢复:for i in mytestserver;做 ssh $i 'nohup tail -f /log/log.log | python /test/deliver.py > /dev/null 2>&1 &';完成
  • 我有点惊讶ssh 在远程命令结束时没有退出,但也许你需要强制退出。您可以尝试将exit 粘贴在引用命令的末尾(但在此处不起作用的快速测试中),因此您可能需要将-f 参数改为ssh。同样循环/etc/hosts 似乎是一个可怕的想法,因为它可能会多次访问本地主机以及每个主机。更何况你shouldn't read lines with for
  • 谢谢,exit 或 -f 也没有运气(我有 cat /etc/hosts 的 grep 和 awk 命令,尽量保持简单,不显示公司敏感信息)

标签: bash loops for-loop background nohup


【解决方案1】:

就像 Etan Reisner 在 cmets 中已经指出的那样,您需要远程运行整个命令。此外,您需要从ssh 命令行中分离标准输入。

最后,for 循环是错误的形式;使用while 从面向行的输入文件中读取。

while read -r host; do
    ssh "$host" 'nohup tail -f /log/log.log |
        python /test/deliver.py > /dev/null 2>&1 &' </dev/null
done </etc/hosts

(虽然在我见过的机器上,/etc/hosts的格式并不真正适合这种处理。也许只读取第一个字段并丢弃其他字段?这很容易;while read -r host _; do...)

【讨论】:

  • 您可能还想至少在调试时取出&gt;/dev/null 2&gt;&amp;1
  • 如果此诊断正确,则此问题与 stackoverflow.com/questions/29142/… 重复
  • Ty 三人组,这让我到达了我需要的地方,请参阅原始问题中的编辑
  • 请不要发布问题的答案。如果您想发布自己的答案,那很好。
【解决方案2】:

我对此没有任何问题:

$ for i in {1..5}; do ssh -i me@ip nohup sleep 10 >/dev/null 2>&1 &
 => done
[7] 34057
[8] 34058
[9] 34059
[10] 34060
[11] 34061
$ #
[7]   Done                        
[8]   Done                        
[9]   Done                        
[10]   Done                        
[11]   Done

【讨论】:

  • 您将本地的ssh 命令置于后台。那不是OP正在做的事情。虽然这可能是他们应该做的,但我不这么认为。我认为他们想要的是 -f 选项(同样的想法)。
猜你喜欢
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 2020-01-06
相关资源
最近更新 更多