Node.js ssh2-exec的输出被截断

时间:2019-02-18 15:37:13

标签: node.js ssh2-exec

有人可以帮助我了解为什么在使用result[ip] = data.toString();而不是console.log(data.toString());时ssh命令输出被截断吗?我只获得前50个字节左右的对象分配,但是console.log可以获取所有内容。我使用Promise / await的原因是因为我计划最终将其同时传播给多个主机,并在继续之前使用Promise.all获得结果。

#!/usr/local/bin/node
var fs = require('fs');
var ssh_client = require('ssh2').Client;


var ssh_config = {
    port: 22,
    username: 'username',
    password: 'password',
    readyTimeout: 5000 };
var cmd = 'find /home/username -type f -iname "*.txt"';


async function main() {
    let ip = '10.10.10.110';
    let result = await sshExec(ip);
    console.log(result[ip]);
}


function sshExec(ip) {
    return new Promise(function(resolve, reject) {
        let ssh = new ssh_client();
        let config = Object.assign(ssh_config, {'host': ip});
        let result = {};

        ssh.connect(config);

        ssh.on('ready', function() {
            console.log("Connected to " + ip + ".");
            ssh.exec(cmd, function(err, stream) {
                if (err) throw err;
                stream.on('data', function(data) {
                    //console.log(data.toString());
                    result[ip] = data.toString();
                }).stderr.on('data', function(data) {
                    console.log('STDERR: ' + data);
                }).on('close', function(code, signal) {
                    ssh.end();
                });
            });
        });

        ssh.on('error', function(e) {
            console.log(ip + ', connection failed, ' + e.message);
        });

        ssh.on('close', function(hadError) {
            if (!hadError) {
                console.log('Connection to ' + ip + ' closed without errors.');
                resolve(result);
            }
            else {
                console.log('Connection to ' + ip + ' closed with errors.');
                reject(result.ip = 'failure');
            }
        });
    });
}


main();

0 个答案:

没有答案