usersam
usersam

Reputation: 1245

nodejs execute command on remote linux server

From nodejs I have been trying to execute linux commands on remote server and get the output in stream for further processing. For connecting to remote linux server , I have all necessary details like serverip, username and password. I searched a lot on internet and found that this can be achieved by ssh.

Can Nodejs ui page run shell cmd to remote machine and run script

But this answer a bit confusing and I didn't get how to use password in connection.

Pointer to any working example would be great help.

Upvotes: 12

Views: 29120

Answers (5)

Feiga Lubow
Feiga Lubow

Reputation: 332

For me the simplest way worked :

Run the ssh commnad from process_child.exec like executing it from bash :

    const childProcess = require('child_process');
    const util = require('util');
    const exec = util.promisify(childProcess.exec).bind(childProcess);
    async function connect() {
        
     try{
       let stdout = await exec(`sudo chmod 400 /home/ubuntu/.ssh/id_rsa
          sudo ssh -i "/home/ubuntu/.ssh/id_rsa" [email protected] ls`);
       console.log(stdout);
     }catch(err){
       console.log('error' , err)
     }
   }
        
   connect();

Upvotes: 1

nbs
nbs

Reputation: 319

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

Upvotes: 1

usersam
usersam

Reputation: 1245

I also used another package "simple-ssh" to solve this purpose. It is very simple to use and gives good control over output which can be used like a stream.

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

var ssh = new SSH({
    host: 'XX.XX.XX.XXX',
    user: 'username',
    pass: 'password'
});

ssh.exec('ls -lh', {
    out: function(stdout) {
        console.log(stdout);
    }
}).start();

And to END execution on demand

ssh.end();

Where ssh is nothing but the new SSH we have declared previously.

Upvotes: 6

Nikhil Jain
Nikhil Jain

Reputation: 619

Node comes with this default library 'remote-exec', which can be used for remote ssh. It worked for me.

var rexec = require('remote-exec');

module.exports = function (context, req) {
    var connection_options = {
    port: 443,
    username: 'yourusername',
    password: 'yourpassword'
    };

    var hosts = [
        'yourhostname.com'
    ];

    var cmds = [
     'ls -lh'
    ];

    rexec(hosts, cmds, connection_options, function(err){
        if(err){
            context.log(err);
        }else{
         context.log("Success!!");
        }
    });
};

Upvotes: 3

usersam
usersam

Reputation: 1245

I solved the problem myself. There is one npm package (ssh-exec) available for ssh command execution. Below is the code I used.

var exec = require('ssh-exec')
var v_host = 'XX.XX.XX.XXX'
exec('ls -lh', {
  user: 'root',
  host: 'XX.XX.XX.XXX', 
  password: 'password'
}).pipe(process.stdout , function (err, data) {
    if ( err ) { console.log(v_host); console.log(err); }
  console.log(data)
})

Upvotes: 12

Related Questions