came across this post while looking for solution to execute a script on remote [aws] Linux server. Used ssh2 package and the below code worked good -
var Client = require('ssh2').Client;
var conn = new Client();
conn.on('ready', function() {
console.log('Client :: ready');
// const cmd = 'uptime';
const cmd = 'ls -l /tmp | grep jetty';
conn.exec(cmd , function(err, stream) {
if (err) throw err;
stream.on('close', function(code, signal) {
console.log('SSH Stream :: close :: code: ' + code + ', signal: ' + signal);
conn.end();
}).on('data', function(data) {
console.log('STDOUT: ' + data);
}).stderr.on('data', function(data) {
console.log('STDERR: ' + data);
});
});
}).connect({
host: 'ec2-##-###-###-###.ap-xxxx-1.compute.amazonaws.com',
username: 'xyz',
privateKey: require('fs').readFileSync('../my_private.ppk')
});
ref: https://www.npmjs.com/package/ssh2
also install ssh2 using npm i ssh2
sample run of the above:
E:\nodejs>node ex-ssh2.js
Client :: ready
STDOUT: drwxr-xr-x 2 jenkins jenkins 4096 Jul 17 13:35 jetty-0.0.0.0-8080-war-_-any-3087978102711715755.dir
SSH Stream :: close :: code: 0, signal: undefined