MaiaVictor
MaiaVictor

Reputation: 52957

How to SSH into a server from a node.js application?

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

exec('ssh my_ip',function(err,stdout,stderr){
    console.log(err,stdout,stderr);
});

This just freezes - I guess, because ssh my_ip asks for password, is interactive, etc. How to do it correctly?

Upvotes: 4

Views: 30973

Answers (5)

Steel Brain
Steel Brain

Reputation: 4461

The other library on this page has a lower level API.

So I've wrote a lightweight wrapper for it. node-ssh which is also available on GitHub under the MIT license.

Here's an example on how to use it.

var driver, ssh;

driver = require('node-ssh');

ssh = new driver();

ssh.connect({
  host: 'localhost',
  username: 'steel',
  privateKey: '/home/steel/.ssh/id_rsa'
})
.then(function() {
  // Source, Target
  ssh.putFile('/home/steel/.ssh/id_rsa', '/home/steel/.ssh/id_rsa_bkp').then(function() {
    console.log("File Uploaded to the Remote Server");
  }, function(error) {
    console.log("Error here");
    console.log(error);
  });
  // Command
  ssh.exec('hh_client', ['--check'], { cwd: '/var/www/html' }).then(function(result) {
    console.log('STDOUT: ' + result.stdout);
    console.log('STDERR: ' + result.stderr);
  });
});

Upvotes: 4

Josh
Josh

Reputation: 1267

pure js/node way to ssh into hosts. Special thanks to ttfreeman. assumes ssh keys are on host. No need for request object.


const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
require('dotenv').config()

//SSH into host and run CMD 
const ssh = async (command, host) => {
let output ={};
  try {
    output['stdin'] = await exec(`ssh -o -v ${host} ${command}`)
  } catch (error) {
    output['stderr'] = error.stderr
  }

  return output
}


exports.ssh = ssh



Upvotes: -1

ttfreeman
ttfreeman

Reputation: 5533

The best way is to use promisify and async/await. Example:

const { promisify } = require('util');
const exec = promisify(require('child_process').exec);

export default async function (req, res) {
  const { username, host, password } = req.query;
  const { command } = req.body;

  let output = {
    stdout: '',
    stderr: '',
  };

  try {
    output = await exec(`sshpass -p ${password} ssh -o StrictHostKeyChecking=no ${username}@${host} ${command}`);
  } catch (error) {
    output.stderr = error.stderr;
  }

  return res.status(200).send({ data: output, message: 'Output from the command' });
}

Upvotes: 0

Flavio Salas
Flavio Salas

Reputation: 350

Check my code:

// redirect to https:
app.use((req, res, next) => {
    if(req.connection.encrypted === true) // or (req.protocol === 'https') for express
        return next();

    console.log('redirect to https => ' + req.url);
    res.redirect("https://" + req.headers.host + req.url);
});

Upvotes: -1

Andrew Ty.
Andrew Ty.

Reputation: 677

There's a node.js module written to perform tasks in SSH using node called ssh2 by mscdex. It can be found here. An example for what you're wanting (from the readme) would be:

var Connection = require('ssh2');

var c = new Connection();
c.on('connect', function() {
  console.log('Connection :: connect');
});
c.on('ready', function() {
  console.log('Connection :: ready');
  c.exec('uptime', function(err, stream) {
    if (err) throw err;
    stream.on('data', function(data, extended) {
      console.log((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ')
                  + data);
    });
    stream.on('end', function() {
      console.log('Stream :: EOF');
    });
    stream.on('close', function() {
      console.log('Stream :: close');
    });
    stream.on('exit', function(code, signal) {
      console.log('Stream :: exit :: code: ' + code + ', signal: ' + signal);
      c.end();
    });
  });
});
c.on('error', function(err) {
  console.log('Connection :: error :: ' + err);
});
c.on('end', function() {
  console.log('Connection :: end');
});
c.on('close', function(had_error) {
  console.log('Connection :: close');
});
c.connect({
  host: '192.168.100.100',
  port: 22,
  username: 'frylock',
  privateKey: require('fs').readFileSync('/here/is/my/key')
});

Upvotes: 6

Related Questions