【问题标题】:Synchronized ssh in the background后台同步ssh
【发布时间】:2019-12-07 23:30:43
【问题描述】:

这是对以下问题的跟进: Executing ssh command in a bash shell script within a loop

我正在做类似的工作:

while read line
do
   ssh -n root@$line 'command'
   do something
done

问题是我只想在前一个 ssh 行中的“命令”执行完成时才执行“做某事”部分,即我想等到后台 ssh 完成。 我可以使用睡眠,但这不适合我的应用程序。请指导我。

我不想特别在后台运行 ssh。我这样做只是为了让我的循环正常运行。如Executing ssh command in a bash shell script within a loop 如果我们不给出 -n 标志,则循环在第一次 ssh 命令执行后终止。

【问题讨论】:

  • 问题解决了。一点谷歌搜索帮助我: while read line do ssh root@$line 'command' 72.14.189.113/howto/shell/while-ssh

标签: bash ssh


【解决方案1】:

如果您的命令未在后台运行,则执行 ssh server command 将等待该命令完成。例如,试试这个:

ssh server "sleep 3"
echo finished

这将在sleep 3 在远程服务器上实际执行后打印“完成”(即 3 秒后)。

试试这个 - 在 ~/tmp 中创建三个文件 - 称为行,parent.sh 和 child.sh。要进行测试,请在运行 sshd 的机器上进行测试,这样您就可以使用 ssh localhost 而不是 ssh server。把它放进去:

  • line1
    line2
    line3
    
  • parent.sh

    while read l; do
      echo next line
      ssh -n localhost "~/tmp/child.sh $l"
    done < lines
    echo parent
    
  • child.sh

    echo child processing: $1
    sleep 2
    echo child done
    

当你运行父级时:

$ cd ~/tmp
$ ./parent.sh

输出将是这样的:

next line
child processing: line1
child done
next line
child processing: line2
child done
next line
child processing: line3
child done
parent

这表明子进程将在父进程继续处理下一行之前执行。您将在“child processing”和“child done”行之间看到 2 秒的休眠(sleep 2 在 child.sh 中执行的结果)。

注意ssh -n 不是为了在后台运行ssh - 它是为了不使用标准输入。要在后台运行 ssh,可以使用 ssh -f - 请参阅 man ssh

【讨论】:

  • 我已经编辑了问题并添加了为什么我在后台执行 ssh。我想以某种方式找到一种方法,以便循环运行而不在后台运行 ssh,或者找到某种方法来检测此 ssh 进程的完成。
  • 查看我的编辑 - 请尝试我放在那里的内容,看看是否如您所愿。
  • 你是对的 - -n 有助于消耗标准输入。我已经使用 /dev/null 来读取输入,并且代码在没有 -n 的情况下运行良好。
【解决方案2】:

一点谷歌搜索帮助我:

while read line
do
   ssh root@$line 'command' < /dev/null
   do something
done

这样就不需要 -n 标志了。 更多细节: http://72.14.189.113/howto/shell/while-ssh/

【讨论】:

  • -n 标志应该没有问题 - 与-f 标志不同,它仍然在前台运行。
猜你喜欢
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多