我正在使用 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/