简体   繁体   English

NodeJS中远程主机上的Spawn进程

[英]Spawn process on remote host in NodeJS

I have a simple Node server that serves a page with a button. 我有一个简单的节点服务器,该服务器提供带有按钮的页面。 On click that button needs to execute a command on a remote host. 单击时,该按钮需要在远程主机上执行命令。 When the command finishes, the output should then be given to the response of the function and shown in the html. 命令完成后,应将输出提供给函数响应并显示在html中。

Currently this is the server code: 当前,这是服务器代码:

app.use(logger("combined"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/index.html', function (req, res) {
    res.sendFile( __dirname + "/" + "index.html" );
})

app.post('/connect', function (req, res) {
    var spawn = require('cross-spawn-async');
    var mpiProc = spawn('ssh','pi@raspi2','"ls"', { stdio: ['pipe','pipe',2,'pipe'] });

    var grid = "...8.1..........435............7.8........1...2..3....6......75..34........2..6..";
    str = "";
    mpiProc.stdout.on('data', function(data) {
        console.log(data);
        str = data.toString();
        res.write('data: ' + JSON.stringify({ msg : str }) + '\n\n');
        // Output       
    });

    mpiProc.on('close', function(code) {
        res.end(str);
        // Script exit code
    });

    mpiProc.on('error', function(code) {
        res.end('stderr: ' + code);
        // Script exit code
    });
}) 
    require('http').createServer(app).listen(3000, function(){
    console.log('Listening on 3000');
});

As you can see the following call tries to execute the 'ls' command on a remote host: 如您所见,以下调用尝试在远程主机上执行“ ls”命令:

var mpiProc = spawn('ssh','pi@raspi2','"ls"', { stdio: ['pipe','pipe',2,'pipe'] });

But this doesn't return anything, while executed from the server directly from terminal, it returns the list of directory content. 但这不会返回任何内容,而直接从终端从服务器执行该操作时,它将返回目录内容的列表。 To test if the command works this way with a spawn I tried doing this: 为了测试该命令是否与衍生工具一起工作,我尝试这样做:

var mpiProc = spawn('ls', { stdio: ['pipe','pipe',2,'pipe'] });

Which returns what I expected, the list of directory content on the server. 它返回我期望的内容,即服务器上的目录内容列表。 So how can I create a pipe to a remote host to execute a command and then store the result of the command on the server? 那么,如何创建到远程主机的管道来执行命令,然后将命令的结果存储在服务器上?

The second argument passed to spawn() is an array of arguments. 传递给spawn()的第二个参数是参数数组。 Also, you don't need to manually quote your arguments. 另外,您无需手动引用参数。 This should work: 这应该工作:

spawn('ssh', ['pi@raspi2', 'ls'], { stdio: ['pipe', 'pipe', 2, 'pipe'] });

Lastly, if you want more programmatic (and lightweight) control over the ssh connection, there is the ssh2 module (or any of the modules that build on top of it), which does not use child processes. 最后,如果您想对ssh连接进行更多的编程(和轻量级)控制,可以使用不使用子进程的ssh2模块(或在其之上构建的任何模块)。

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

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