这是我小兄弟的测试代码,我直接拿来贴了,哈哈哈
var Connection = require('ssh2');
const { createUnzip } = require('zlib');
var con = new Connection()
con.on('ready', function() {
console.log('Connection :: ready');
con.shell(function(err, stream) {
if (err) {
console.log('err over ')
} else {
var buf = '';
var bData = false;
stream.on('data', function(data) {
if (bData == false) {
bData = true;
stream.write('su\n');
}
if (data.indexOf('Password:') > -1) {
stream.write('Pxxxxxxxx')
}
console.log(data.toString())
if (data.indexOf('# ') > -1) {
console.log('成功了')
stream.end()
}
}).on('close', function() {
console.log('success over ')
}).stderr.on('data', function(data) {
console.log('stderr: ' + data);
});
}
});
});
con.on('error', function(err) {
console.log('Connection :: error :: ' + err);
});
con.on('end', function() {
console.log('Connection :: end');
});
con.on('close', function(had_error) {
console.log('Connection :: close');
});
con.connect({
host: '172.18.xx.xx',
port: 22,
username: 'root',
password: 'Pxxxxxxxx'
})