Jorge Jorge - 1 year ago 238
Node.js Question

SSH2 library, how to execute unix comands from NODE

I am trying to understand about the SSH2 for nodeJS, but I can't find more documentation, does anybody has more related to the client events?

I am trying to connect from my Node project to a Unix server and execute commands from node using this library SSH2 such as mkdir, ls or some other unix commands but I can't find any documentation of how to do it.

I am able to establish connection, but now I need to execute unix commands

var Client = require('ssh2').Client;
var conn = new Client();
conn.on('ready', function() {
console.log('Client :: ready');
conn.sftp(function(err, sftp) {
if (err) throw err;
console.log('Client :: SSH open');
host: 'hostname',
port: 22,
username: 'user',
password: 'password'

Or if this is not achievable with SSH2 can somebody recommend another Node Library were I can connect to an unix server? I have a Node application that creates a HTML file but after the creation I need to name it in base of the last file name that I have in a unix server, create the directory in unix and the upload it using sftp-upload plugin. Trying to achieve this with node instead of doing manually.

I appreciate the help

Answer Source

You can do this with node-exec or ssh2-exec which uses ssh2. ssh2 is low level so for exec you can use other libs like ssh2-exec and ssh2-connect.

There are plenty of examples in

Example (from ssh2-exec README):

connect = require('ssh2-connect');
exec = require('ssh2-exec');
connect({host: localhost}, function(err, ssh){
  child = exec({cmd: 'ls -la', ssh: ssh}, function(err, stdout, stderr){
  child.stdout.on('data', function(data){
  child.on('exit', function(code){
    console.log('Exit', code);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download