node.js - 在 Node.js SSH2 中发送终止 (Ctrl+C) 命令

标签 node.js ssh

我正在使用 Node.js SSH2 模块( https://github.com/mscdex/ssh2 )。 myScript.py 连续执行。如何在保持 SSH 连接处于事件状态的同时停止它?

var Connection = require('ssh2');
var c = new Connection();
c.on('ready', function() {
  c.exec('python myScript.py', function(err, stream) {
    if (err) throw err;
    stream.on('data', function(data, extended) {
      //this callback gets called multiple times as the script writes to stdout
      console.log((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ') + data);
      allData+=data;
    });
  });
});
c.connect({
  host: xxx.xxx.x.xx,
  port: 22,
  username: 'user',
  password: 'pass'
});

最佳答案

我们的研究组也遇到了同样的问题,我们的解决方案是在第一次执行命令时获取远程进程的进程ID,然后在需要时杀死它。

如果你只使用kill [pid],Python进程似乎会继续在后台独立运行。命令,因此我们使用 pkill -g [pid]下面我们的解决方案中的命令。在其他情况下这可能不同或相同。但我想,如果其中一种情况不适合您,那么您应该尝试这两种情况,这是件好事。

这是我们的(简化的)解决方案。当然,在 5 秒后终止每个 exec 命令是没有意义的......但您会明白这个想法(以及一个安全的 pid/conn 重用范围):

var Connection = require('ssh2');
var c = new Connection();

function killProcess(conn, pid) {
    setTimeout(function() {
        console.log('Killing PID ' + pid);
        conn.exec('pkill -g ' + pid, function(){});
    }, 5000);
}

c.on('ready', function() {
    // echo $$; gives you the PID, we prepend it with the string
    // "EXEC PID: " to later on know for sure which line we grab as PID
    c.exec('echo "EXEC PID: $$";python myScript.py', function(err, stream) {
        if(err) throw err;
        stream.on('data', function(buffer) {
            var line = '' + buffer; // unbeautiful ;)
            console.log(line);
            if(line.substr(0, 10) === 'EXEC PID: ') {
                killProcess(c, line.substr(10));
            }
        }).on('end', function() {
            console.log('exec killed');
        });
    });
});
c.connect({
  host: xxx.xxx.x.xx,
  port: 22,
  username: 'user',
  password: 'pass'
});

关于node.js - 在 Node.js SSH2 中发送终止 (Ctrl+C) 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22164570/

相关文章:

javascript - 为什么我的 req.body 在 POST 时总是为空?

node.js - 如何加载commonJS模块的子路径?

git - 使用 Git 的最佳方式是什么,是通过 HTTPS 还是通过 SSH?

支持putty生成 key 的java ssh库

Bash 脚本 "read"从 SSH shell 执行时不暂停用户输入

node.js - 使用外部 babel 配置会破坏 Node/React 应用程序 - 内部服务器错误

javascript - 修改公共(public) npm 包中的一些功能

ssh - Gitlab CI - SSH 权限被拒绝(公钥、密码)

windows - 在 Windows 下使用 ssh 克隆 github.com 的 repo 时出现 "no address associated with name"错误

javascript - 在 NodeJS 中使用变换/双工流