我需要我的nodejs应用在远程服务器上运行命令,所以我正在使用此节点ssh库
https://github.com/mscdex/ssh2
由于我需要在同一连接上运行多个命令,因此我使用的是shell函数,而不是示例中的exec函数。
我的代码如下
var Connection = require('ssh2');
var commands = [
'uptime',
'ls'
];
var command = "";
var pwSent = false;
var sudosu = false;
var password = 'password';
var conn = new Connection();
conn.on('ready', function () {
console.log('Connection :: ready');
conn.shell(function (err, stream) {
if (err) throw err;
stream.on('close', function () {
console.log('Stream :: close');
conn.end();
}).on('data', function (data) {
//handle sudo password prompt
if (command.indexOf("sudo") !== -1 && !pwSent) {
//if sudo su has been sent a data event is triggered but the first event is not the password prompt
//this will ignore the first event and only respond when the prompt is asking for the password
if (command.indexOf("sudo su") > -1) {
sudosu = true;
}
if (data.indexOf(":") >= data.length - 2) {
pwSent = true;
stream.write(password + '\n');
}
} else {
//detect the right condition to send the next command
var dataLength = data.length
if (dataLength > 2 && (data.indexOf("$") >= dataLength - 2 || data.indexOf("#") >= dataLength - 2)) {
if (commands.length > 0) {
command = commands.shift();
stream.write(command + '\n');
} else {
//sudo su requires two exit commands to close the session
if (sudosu) {
sudosu = false;
stream.write('exit\n');
} else {
stream.end('exit\n');
}
}
} else {
console.log('STDOUT: ' + data);
}
}
}).stderr.on('data', function (data) {
console.log('STDERR: ' + data);
});
//first command
command = commands.shift();
//console.log "first command: " + command;
stream.write(command + '\n');
});
}).connect({
host: 'xx.xxx.xx.xxx',
port: 22,
username: 'user',
password: 'password'
});
但是我只得到某些命令的标准输出,有时根本没有,
Connection :: ready
STDOUT: Last login: Tue Feb 11 20:43:58 2020 from xx.xx.xx.xx
STDOUT: uptime
STDOUT: [user@server ~]# uptime
STDOUT: ls
STDOUT: exit
logout
Stream :: close
我的问题是,是否应该返回终端的完整输出,以及为什么我的代码无法做到这一点