Remote command execution via SSH using NodeJS

0
18368
NodeJS
NodeJS

In this post, I’d like to share a small tip to develop a small utility to remote command execution via SSH using NodeJS.

I often have to deal with server remote control, so sometimes manually remote SSH to server to execute command is not a good option. Therefore, I write some small scripts to handle task via code instead of doing manually.

In NodeJS, you can use simple-ssh package to handle SSH connection.  To install it into project,


$ npm install --save simple-ssh

and load into project.


const SSH = require('simple-ssh');

First step is to create an instance of SSH:


var ssh = new SSH({
    host: 'IP_ADDRESS',
    user: 'USERNAME',
    pass: 'PASSWORD'
});

Via initialization, just provide necessary credentials to connect to SSH Server. So now, we can issue any command to SSH server via exec command.


ssh.exec(CMD, {
    out: function (stdout) { console.log(stdout); },
    err: function (stderr) { console.log(stderr); },
    exit: function (code) { console.log(code); }
}).start();

Command to be executed should be passed in the first parameter, the 2nd parameter is an object of callback to handle for retrieving command output from STDIN, or error from STDERR, and exit code after command executed; method start should be chained afterward in order to request execution immediately, otherwise, command will not be executed, it is queued instead.

For example, if you want to view content of a directory, then command should be written as following:


ssh
  .exec('ls -asl /home/petehouston', { out: function (stdout) { console.log(stdout); } })
  .start();

This way, you can automate almost anything on SSH server without executing manually.