user7888003
user7888003

Reputation: 13

SSH into remote machine and execute commands in Node.js

I'm looking for a way to SSH into a virtual machine and then execute certain scripts inside the virtual machine using Node.js

So far I've created the shell script that automate the login to the virtual machine but i'm unable to figure out how to move forward.

My shell script for login to remote server

spawn ssh root@localhost
expect "password"
send "123456"
send "\r"
interact

This is my server.js

var http = require('http');
var execProcess = require("./exec_process.js");
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  execProcess.result("sh sshpass.sh", function(err, response){
        if(!err){
            res.end(response);
        }else {
            res.end("Error: ", err);
        }
    });
}).listen(3000);
console.log('Server listening on port 3000');

exec_process.js

var exec = require('child_process').exec;

var result = function(command, cb){
    var child = exec(command, function(err, stdout, stderr){
        if(err != null){
            return cb(new Error(err), null);
        }else if(typeof(stderr) != "string"){
            return cb(new Error(stderr), null);
        }else{
            return cb(null, stdout);
        }
    });
}

exports.result = result;

Any help is appreciated thanks

Upvotes: 1

Views: 15686

Answers (1)

EMX
EMX

Reputation: 6219

Why dont you use simple-ssh ?

I made a simple example of how to load a file with a list of commands and execute them in chain.

exampleList : (commands must be separated in new lines)

echo "Testing the first command"
ls

sshtool.js : (it can be buggy, example: if any command contains \n)

const _ = require("underscore");
//:SSH:
const SSH = require('simple-ssh');
const ssh = new SSH({
    host: 'localhost',
    user: 'username',
    pass: 'sshpassword'
});
//example usage : sshtool.js /path/to/command.list
function InitTool(){
 console.log("[i] SSH Command Tool");
 if(process.argv[2]){AutomaticMode();}
 else{console.log("[missing argument : path to file containing the list of commands]");}
}
//:MODE:Auto
function AutomaticMode(){
 const CMDFileName = process.argv[2];
 console.log("  ~ Automatic Command Input Mode");
 //Load the list of commands to be executed in order
 const fs = require('fs');
 fs.readFile(process.argv[2], "utf8", (err, data) => {
  if(err){console.log("[!] Error Loading Command List File :\n",err);}else{
    var CMDList = data.split("\n"); // split the document into lines
    CMDList.length = CMDList.length - 1; //fix the last empty line
    _.each(CMDList, function(this_command, i){
      ssh.exec(this_command, {
       out: function(stdout) {
        console.log("[+] executing command",i,"/",CMDList.length,"\n  $["+this_command+"]","\n"+stdout);
       }
      });
    });
    console.log("[i]",CMDList.length,"commands will be performed.\n");
    ssh.start();
  }
 });
}
//:Error Handling:
ssh.on('error', function(err) {
 console.log('[!] Error :',err);
 ssh.end();
});

InitTool();

It uses underscore for looping through the command list.

Upvotes: 1

Related Questions