简体   繁体   English

NodeJS child_process:在ssh和流输出上并行运行两个进程

[英]NodeJS child_process: run two process in parallel over ssh and stream outputs

First off, this could have been easily accomplished with ssh2 , but I could not use it because it does not support certificate authentication . 首先,使用ssh2可以轻松完成此操作,但是由于它不支持证书身份验证 ,因此我无法使用它。

Hence the problem at hand: 因此,眼下的问题是:

I am using child_process to run the ssh binary and connect to a remote server. 我正在使用child_process运行ssh binary并连接到远程服务器。 I can run commands and get their outputs via stdin and stdout of the spawned process. 我可以运行命令并通过生成的进程的stdinstdout获取它们的输出。 But I have a use case where I need to run two commands in parallel . 但是我有一个用例,其中我需要并行运行两个命令 One is a long running command which I need to stream line by line and the other is a lightweight command whose input depends on the contents of the streamed lines. 一个是运行时间很长的命令,我需要逐行流式传输,另一个是轻量级命令,其输入取决于流式传输的行的内容。 Is it possible to do this without spawning two ssh processes? 是否可以在不产生两个 ssh进程的情况下做到这一点?

Workarounds using ssh2 or something similar are also welcome. 也欢迎使用ssh2或类似方法来解决。

(Edit)Adding a descriptive example: (编辑)添加一个描述性示例:

Process 1 is long running and keeps writing lines to stdout/file, Process 2 needs to run on each line as whenever a line is produced by Process 1 . Process 1运行很长时间,并且一直在向stdout / file写入行, Process 2需要像在Process 1产生一行时一样在每行上运行。 At each point, when Process 2 for a line completes, I need both input line printed by Process 1 and the corresponding output of Process 2 在每一点上,当某行的Process 2完成时,我需要input line printed by Process 1the corresponding output of Process 2

there is a very simple way: use gnu parallel. 有一个非常简单的方法:使用gnu并行。 https://www.gnu.org/software/parallel/ It is installed on Ubuntu fe with sudo apt -y install parallel https://www.gnu.org/software/parallel/使用sudo apt -y install parallel安装在Ubuntu fe上

ssh host \
  'echo -e "date > 1.out && sleep 5\n date > 2.out && sleep 5" | parallel -j0'
ssh host cat 1.out
    > Th 14. Jun 10:54:15 CEST 2018
ssh host cat 2.out
    > Th 14. Jun 10:54:15 CEST 2018

Now you could ssh to cat 1.out and 2.out. 现在,您可以使用ssh命令访问1.out和2.out。

But let's consider your later edit: 但是,让我们考虑一下您以后的编辑:

prog1.sh: prog1.sh:

for i in {1..5}; do
  echo $i >> 1.out
  sleep 1;
done
echo "done" >> 1.out
sleep 1
echo -e "\n" >> 1.out

prog2.sh (monitors 1.out and does some command, here tail): prog2.sh(监视1.out并执行一些命令,此处为尾部):

inotifywait -e close_write,moved_to,create -m . |
  while read -r directory events filename; do
    if [ "$filename" = "1.out" ]; then
      # 1.out changed we need to do something
      res=$(tail -1 1.out)
        if [ $res = "done" ]; then
            break;
        fi
      fi
  done

ssh host 'echo -e "./prog2.sh \n ./prog1.sh" | parallel -j 2'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM