ssh2 by Brian White is the module for SSH networking in Node.js and is written completely in JavaScript. If you want to do anything SSH related, odds are ssh2 can do it for you.
Here’s a list of things it can do as to give you an idea of its flexibility:
- Authenticate using keys and execute uptime on a server
- Authenticate using keys and start an interactive shell session
- Authenticate using password and send an HTTP request to port 80 on the server
- Authenticate using password and forward remote connections on port 8000 to us
- Authenticate using password and get a directory listing via SFTP
- Connection hopping
- Forward X11 connections (xeyes)
- Dynamic (1:1) port forwarding using a SOCKSv5 proxy (using socksv5)
- Invoke an arbitrary subsystem (netconf in this example)
npm install ssh2
Usage
ssh2 is pretty much based on Node.js steams and most operations involve either reading or writing to a stream. Example below executed find /etc
on a local SSH connection and outputs the results.
var Connection = require('ssh2');
var conn = new Connection();
function onReady() {
conn.exec('find /etc', onExec);
}
function onExec(err, stream) {
if (err) throw err;
stream.on('exit', function(code, signal) {
console.log('Stream :: exit :: code: ' + code + ', signal: ' + signal);
});
stream.on('close', function() {
console.log('Stream :: close');
conn.end();
});
stream.on('data', function(data) {
console.log('STDOUT: ' + data);
});
stream.stderr.on('data', function(data) {
console.log('STDERR: ' + data);
});
}
conn.connect({
host: '127.0.0.1',
port: 22,
username: 'test_user',
password: 'qwerty'
});
conn.on('ready', onReady);
What Else?
Checkout the runnable example and github example repository.