SSH2库,如何从NODE执行unix命令

时间:2016-02-23 15:29:11

标签: javascript node.js unix ssh

我正在尝试了解nodeJS https://github.com/mscdex/ssh2的SSH2,但我找不到更多文档,是否有人与客户事件有更多关联?

我正在尝试从我的Node项目连接到Unix服务器并使用此库SSH2执行来自节点的命令,例如mkdir,ls或其他一些unix命令,但我找不到任何关于如何操作的文档。 / p>

我能够建立连接,但现在我需要执行unix命令

var Client = require('ssh2').Client;
//
var conn = new Client();
conn.on('ready', function() {
    console.log('Client :: ready');
    conn.sftp(function(err, sftp) {
        if (err) throw err;
        console.log('Client :: SSH open');
        output.add("ls");
        conn.end();
    });
}).connect({
    host: 'hostname',
    port: 22,
    username: 'user',
    password: 'password'
});

或者,如果使用SSH2无法实现这一点,我可以推荐另一个节点库,我可以连接到unix服务器吗?我有一个创建HTML文件的Node应用程序但是在创建之后我需要根据我在unix服务器中的最后一个文件名来命名它,在unix中创建目录并使用sftp-upload插件上传它。尝试使用节点而不是手动执行此操作。

1 个答案:

答案 0 :(得分:0)

您可以使用node-exec或使用ssh2的{​​{3}}执行此操作。 ssh2为低级别,因此对于exec,您可以使用其他库,例如ssh2-execssh2-connect

README.md中有很多例子。

示例(来自ssh2-exec README):

connect = require('ssh2-connect');
exec = require('ssh2-exec');
connect({host: localhost}, function(err, ssh){
  child = exec({cmd: 'ls -la', ssh: ssh}, function(err, stdout, stderr){
    console.log(stdout);
  });
  child.stdout.on('data', function(data){
    console.log(stdout);
  });
  child.on('exit', function(code){
    console.log('Exit', code);
  });
})
相关问题