What is ssh2?
The ssh2 npm package is a client and server module for SSH and SFTP written in pure JavaScript for node.js. It provides an interface to connect to and interact with SSH servers, allowing for the execution of commands, file transfers, local and remote port forwarding, and more.
What are ssh2's main functionalities?
Executing Commands on Remote Server
This code sample demonstrates how to execute a command (in this case, 'uptime') on a remote server using the ssh2 package.
const { Client } = require('ssh2');
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.exec('uptime', (err, stream) => {
if (err) throw err;
stream.on('close', (code, signal) => {
console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
conn.end();
}).on('data', (data) => {
console.log('STDOUT: ' + data);
}).stderr.on('data', (data) => {
console.log('STDERR: ' + data);
});
});
}).connect({
host: '192.168.100.100',
port: 22,
username: 'frylock',
privateKey: require('fs').readFileSync('/here/is/my/key')
});
SFTP File Transfer
This code sample shows how to transfer a file from a local path to a remote path using SFTP with the ssh2 package.
const { Client } = require('ssh2');
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.sftp((err, sftp) => {
if (err) throw err;
sftp.fastPut(localPath, remotePath, {}, (err) => {
if (err) throw err;
console.log('File transferred successfully!');
conn.end();
});
});
}).connect({
host: '192.168.100.100',
port: 22,
username: 'frylock',
privateKey: require('fs').readFileSync('/here/is/my/key')
});
TCP Port Forwarding
This code sample illustrates how to set up TCP port forwarding from the local machine to a remote destination using the ssh2 package.
const { Client } = require('ssh2');
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.forwardOut('127.0.0.1', 12345, 'www.google.com', 80, (err, stream) => {
if (err) throw err;
stream.on('close', () => {
console.log('TCP :: CLOSED');
conn.end();
}).on('data', (data) => {
console.log('TCP :: DATA: ' + data);
});
stream.end('GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n');
});
}).connect({
host: '192.168.100.100',
port: 22,
username: 'frylock',
privateKey: require('fs').readFileSync('/here/is/my/key')
});
Other packages similar to ssh2
node-ssh
node-ssh is an SSH2 client module that provides a higher-level API for interacting with SSH servers. It simplifies tasks like executing commands and handling file transfers. Compared to ssh2, node-ssh is built on top of ssh2 and offers a more promise-based API, which can be easier to use for some developers.
simple-ssh
simple-ssh is another SSH client for node.js that aims to provide a simpler and more intuitive API than ssh2. It offers a chainable API for executing multiple commands in sequence. While it may be easier for beginners, it is not as feature-rich as ssh2 and may not be suitable for more complex SSH interactions.
Description
An SSH2 client module written in pure JavaScript for node.js.
Development/testing is done against OpenSSH (6.1 currently).
Requirements
Install
npm install ssh2
Examples
- Authenticate using keys, execute
uptime
on a server, and disconnect afterwards:
var Connection = require('ssh2');
var c = new Connection();
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')
});
- Authenticate using password, send a (raw) HTTP request to port 80 on the server, and disconnect afterwards:
var Connection = require('ssh2');
var c = new Connection();
c.on('ready', function() {
console.log('Connection :: ready');
c.forwardOut('192.168.100.102', 8000, '127.0.0.1', 80, function(err, stream) {
if (err) throw err;
stream.on('data', function(data) {
console.log('TCP :: DATA: ' + data);
});
stream.on('end', function() {
console.log('TCP :: EOF');
});
stream.on('error', function(err) {
console.log('TCP :: ERROR: ' + err);
});
stream.on('close', function(had_err) {
console.log('TCP :: CLOSED');
c.end();
});
var data = [
'HEAD / HTTP/1.1',
'User-Agent: curl/7.27.0',
'Host: 127.0.0.1',
'Accept: */*',
'Connection: close',
'',
''
];
stream.write(data.join('\r\n'));
});
});
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',
password: 'nodejsrules'
});
- Authenticate using password and forward remote connections on port 8000 to us:
var Connection = require('ssh2');
var c = new Connection();
c.on('tcp connection', function(info, accept, reject) {
console.log('TCP :: INCOMING CONNECTION: ' + require('util').inspect(info));
var stream = accept();
stream.on('data', function(data) {
console.log('TCP :: DATA: ' + data);
});
stream.on('end', function() {
console.log('TCP :: EOF');
});
stream.on('error', function(err) {
console.log('TCP :: ERROR: ' + err);
});
stream.on('close', function(had_err) {
console.log('TCP :: CLOSED');
});
var response = [
'HTTP/1.1 404 Not Found',
'Date: Thu, 15 Nov 2012 02:07:58 GMT',
'Server: ForwardedConnection',
'Content-Length: 0',
'Connection: close',
'',
''
];
stream.end(response.join('\r\n'));
});
c.on('ready', function() {
console.log('Connection :: ready');
c.forwardIn('127.0.0.1', 8000, function(err) {
if (err) throw err;
console.log('Listening for connections on server on port 8000!');
});
});
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',
password: 'nodejsrules'
});
- Authenticate using password, start an SFTP session, and get a directory listing:
var Connection = require('ssh2');
var c = new Connection();
c.on('ready', function() {
console.log('Connection :: ready');
c.sftp(function(err, sftp) {
if (err) throw err;
sftp.on('end', function() {
console.log('SFTP :: SFTP session closed');
});
sftp.opendir('foo', function readdir(err, handle) {
if (err) throw err;
sftp.readdir(handle, function(err, list) {
if (err) throw err;
if (list === false) {
sftp.close(handle, function(err) {
if (err) throw err;
console.log('SFTP :: Handle closed');
sftp.end();
});
return;
}
console.dir(list);
readdir(undefined, handle);
});
});
});
});
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',
password: 'nodejsrules'
});
var Connection = require('ssh2');
var conn1 = new Connection(),
conn2 = new Connection();
conn1.on('ready', function() {
console.log('FIRST :: connection ready');
conn1.exec('nc 192.168.1.2 22', function(err, stream) {
if (err) return console.log('FIRST :: exec error: ' + err);
conn2.connect({
sock: stream,
username: 'user2',
password: 'password2',
});
});
});
conn1.connect({
host: '192.168.1.1',
username: 'user1',
password: 'password1',
});
conn2.on('ready', function() {
console.log('SECOND :: connection ready');
conn2.exec('uptime', function(err, stream) {
if (err) return console.log('SECOND :: exec error: ' + err);
stream.on('data', function(data) {
console.log(data.toString());
});
stream.on('end', function() {
conn1.end();
});
});
});
- Forward X11 connections (xeyes):
var net = require('net'),
Connection = require('ssh2');
var conn = new Connection();
conn.on('x11', function(info, accept, reject) {
var xserversock = new net.Socket();
xserversock.on('connect', function() {
var xclientsock = accept();
xclientsock.pipe(xserversock).pipe(xclientsock);
});
xserversock.connect(6000, 'localhost');
});
conn.on('ready', function() {
conn.exec('xeyes', { x11: true }, function(err, stream) {
if (err) throw err;
var code = 0;
stream.on('end', function() {
if (code !== 0)
console.log('Do you have X11 forwarding enabled on your SSH server?');
conn.end();
});
stream.on('exit', function(exitcode) {
code = exitcode;
});
});
});
conn.connect({
host: '192.168.1.1',
username: 'foo',
password: 'bar'
});
- Invoke an arbitrary subsystem (netconf in this example):
var Connection = require('ssh2'),
xmlhello = '<?xml version="1.0" encoding="UTF-8"?>'+
'<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">'+
' <capabilities>'+
' <capability>urn:ietf:params:netconf:base:1.0</capability>'+
' </capabilities>'+
'</hello>]]>]]>';
var c = new Connection();
c.on('ready', function() {
console.log('Connection :: ready');
c.subsys('netconf', function(err, stream) {
stream.on('data', function(data, extended) {
console.log(data);
});
stream.write(xmlhello);
});
});
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: '1.2.3.4',
port: 22,
username: 'blargh',
password: 'honk'
});
API
require('ssh2')
returns a Connection object
Connection events
-
banner(< string >message, < string >language) - A notice was sent by the server upon connection.
-
ready() - Authentication was successful.
-
tcp connection(< object >details, < function >accept, < function >reject) - An incoming forwarded TCP connection is being requested. Calling accept
accepts the connection and returns a ChannelStream
object. Calling reject
rejects the connection and no further action is needed. details
contains:
-
srcIP - string - The originating IP of the connection.
-
srcPort - integer - The originating port of the connection.
-
dstIP - string - The remote IP the connection was received on (given in earlier call to forwardIn()
).
-
dstPort - integer - The remote port the connection was received on (given in earlier call to forwardIn()
).
-
x11(< object >details, < function >accept, < function >reject) - An incoming X11 connection is being requested. Calling accept
accepts the connection and returns a ChannelStream
object. Calling reject
rejects the connection and no further action is needed. details
contains:
-
keyboard-interactive(< string >name, < string >instructions, < string >instructionsLang, < array >prompts, < function >finish) - The server is asking for replies to the given prompts
for keyboard-interactive user authentication. name
is generally what you'd use as a window title (for GUI apps). prompts
is an array of { prompt: 'Password: ', echo: false }
style objects (here echo
indicates whether user input should be displayed on the screen). The answers for all prompts must be provided as an array of strings and passed to finish
when you are ready to continue. Note: It's possible for the server to come back and ask more questions.
-
change password(< string >message, < string >language, < function >done) - If using password-based user authentication, the server has requested that the user's password be changed. Call done
with the new password.
-
error(< Error >err) - An error occurred. A 'level' property indicates 'connection-socket' for socket-level errors and 'connection-ssh' for SSH disconnection messages. In the case of 'connection-ssh' messages, there may be a 'description' property that provides more detail.
-
end() - The socket was disconnected.
-
close(< boolean >hadError) - The socket was closed. hadError
is set to true if this was due to error.
-
debug(< string >message) - If debug
is set in the object passed to connect(), then this event will be emitted when the server sends debug messages. For OpenSSH, these usually are messages like "Pty allocation disabled.", "X11 forwarding disabled.", etc. when options are set for particular keys in ~/.ssh/authorized_keys
.
Connection methods
Authentication method priorities: Password -> Private Key -> Agent (-> keyboard-interactive if tryKeyboard
is true)
-
exec(< string >command[, < object >options], < function >callback) - (void) - Executes command
on the server. Valid options
properties are:
-
env - < object > - An environment to use for the execution of the command.
-
pty - < mixed > - Set to true to allocate a pseudo-tty with defaults, or an object containing specific pseudo-tty settings (see 'Pseudo-TTY settings'). Setting up a pseudo-tty can be useful when working with remote processes that expect input from an actual terminal (e.g. sudo's password prompt).
-
x11 - < mixed > - Set to true to use defaults below, a number to specify a specific screen number, or an object with the following valid properties:
callback
has 2 parameters: < Error >err, < ChannelStream >stream.
-
shell([[< object >window,] < object >options]< function >callback) - (void) - Starts an interactive shell session on the server, with optional window
pseudo-tty settings (see 'Pseudo-TTY settings'). options
supports the 'x11' option as described in exec(). callback
has 2 parameters: < Error >err, < ChannelStream >stream.
-
forwardIn(< string >remoteAddr, < integer >remotePort, < function >callback) - (void) - Bind to remoteAddr
on remotePort
on the server and forward incoming connections. callback
has 2 parameters: < Error >err, < integer >port (port
is the assigned port number if remotePort
was 0). Here are some special values for remoteAddr
and their associated binding behaviors:
-
'' - Connections are to be accepted on all protocol families supported by the server.
-
'0.0.0.0' - Listen on all IPv4 addresses.
-
'::' - Listen on all IPv6 addresses.
-
'localhost' - Listen on all protocol families supported by the server on loopback addresses only.
-
'127.0.0.1' and '::1' - Listen on the loopback interfaces for IPv4 and IPv6, respectively.
-
unforwardIn(< string >remoteAddr, < integer >remotePort, < function >callback) - (void) - Unbind remoteAddr
on remotePort
on the server and stop forwarding incoming connections. Until callback
is called, more connections may still come in. callback
has 1 parameter: < Error >err.
-
forwardOut(< string >srcIP, < integer >srcPort, < string >dstIP, < integer >dstPort, < function >callback) - (void) - Open a connection with srcIP
and srcPort
as the originating address and port and dstIP
and dstPort
as the remote destination address and port. callback
has 2 parameters: < Error >err, < ChannelStream >stream.
-
sftp(< function >callback) - (void) - Starts an SFTP (protocol version 3) session. callback
has 2 parameters: < Error >err, < SFTP >sftpConnection.
-
subsys(< string >subsystem, < function >callback) - (void) - Invokes subsystem
on the server. callback
has 2 parameters: < Error >err, < ChannelStream >stream.
-
end() - (void) - Disconnects the socket.
ChannelStream
This is a normal streams1 duplex Stream, with the following changes:
-
A boolean property 'allowHalfOpen' exists and behaves similarly to the property of the same name for net.Socket. When the stream's end() is called, if 'allowHalfOpen' is true, only EOF will be sent (the server can still send data if they have not already sent EOF). The default value for this property is false
.
-
For shell():
- setWindow(< integer >rows, < integer >cols, < integer >height, < integer >width) - (void) - Lets the server know that the local terminal window has been resized. The meaning of these arguments are described in the 'Pseudo-TTY settings' section.
-
For exec():
- An 'exit' event will be emitted when the process finishes. If the process finished normally, the process's return value is passed to the 'exit' callback. If the process was interrupted by a signal, the following are passed to the 'exit' callback: null, < string >signalName, < boolean >didCoreDump, < string >description.
-
For shell() and exec():
-
'data' events are passed a second (string) argument to the callback, which indicates whether the data is a special type. So far the only defined type is 'stderr'.
-
signal(< string >signalName) - (void) - Sends a POSIX signal to the current process on the server. Valid signal names are: 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'KILL', 'PIPE', 'QUIT', 'SEGV', 'TERM', 'USR1', and 'USR2'. Also, from the RFC: "Some systems may not implement signals, in which case they SHOULD ignore this message." Note: If you are trying to send SIGINT and you find signal() doesn't work, try writing '\x03' to the exec/shell stream instead.
SFTP events
- end() - The SFTP session was ended.
SFTP methods
-
end() - (void) - Ends the SFTP session.
-
fastGet(< string >remotePath, < string >localPath[, < object >options], < function >callback) - (void) - Downloads a file at remotePath
to localPath
using parallel reads for faster throughput. options
has the following defaults:
-
concurrency - integer - Number of concurrent reads (default: 25)
-
chunkSize - integer - Size of each read in bytes (default: 32768)
-
step - function(< integer >total_transferred, < integer >chunk, < integer >total) - Called every time a part of a file was transferred
callback
has 1 parameter: < Error >err.
-
fastPut(< string >localPath, < string >remotePath[, < object >options], < function >callback) - (void) - Uploads a file from localPath
to remotePath
using parallel reads for faster throughput. options
has the following defaults:
-
concurrency - integer - Number of concurrent reads (default: 25)
-
chunkSize - integer - Size of each read in bytes (default: 32768)
-
step - function(< integer >total_transferred, < integer >chunk, < integer >total) - Called every time a part of a file was transferred
callback
has 1 parameter: < Error >err.
-
createReadStream(< string >path[, < object >options]) - ReadStream - Returns a new readable stream for path
. options
has the following defaults:
{ flags: 'r',
encoding: null,
mode: 0666,
bufferSize: 64 * 1024
}
options
can include 'start' and 'end' values to read a range of bytes from the file instead of the entire file. Both 'start' and 'end' are inclusive and start at 0. The encoding can be 'utf8', 'ascii', or 'base64'.
An example to read the last 10 bytes of a file which is 100 bytes long:
sftp.createReadStream('sample.txt', {start: 90, end: 99});
-
createWriteStream(< string >path[, < object >options]) - WriteStream - Returns a new writable stream for path
. options
has the following defaults:
{ flags: 'w',
encoding: null,
mode: 0666,
autoClose: true
}
options
may also include a 'start' option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a flags mode of 'r+' rather than the default mode 'w'.
If 'autoClose' is set to false and you pipe to this stream, this stream will not automatically close after there is no more data upstream -- allowing future pipes and/or manual writes.
-
open(< string >filename, < string >mode, [< ATTRS >attributes, ]< function >callback) - (void) - Opens a file filename
for mode
with optional attributes
. mode
is any of the modes supported by fs.open (except sync mode). callback
has 2 parameters: < Error >err, < Buffer >handle.
-
close(< Buffer >handle, < function >callback) - (void) - Closes the resource associated with handle
given by open() or opendir(). callback
has 1 parameter: < Error >err.
-
read(< Buffer >handle, < Buffer >buffer, < integer >offset, < integer >length, < integer >position, < function >callback) - (void) - Reads length
bytes from the resource associated with handle
starting at position
and stores the bytes in buffer
starting at offset
. callback
has 4 parameters: < Error >err, < integer >bytesRead, < Buffer >buffer (offset adjusted), < integer >position.
-
write(< Buffer >handle, < Buffer >buffer, < integer >offset, < integer >length, < integer >position, < function >callback) - (void) - Writes length
bytes from buffer
starting at offset
to the resource associated with handle
starting at position
. callback
has 1 parameter: < Error >err.
-
fstat(< Buffer >handle, < function >callback) - (void) - Retrieves attributes for the resource associated with handle
. callback
has 2 parameters: < Error >err, < Stats >stats.
-
fsetstat(< Buffer >handle, < ATTRS >attributes, < function >callback) - (void) - Sets the attributes defined in attributes
for the resource associated with handle
. callback
has 1 parameter: < Error >err.
-
futimes(< Buffer >handle, < mixed >atime, < mixed >mtime, < function >callback) - (void) - Sets the access time and modified time for the resource associated with handle
. atime
and mtime
can be Date instances or UNIX timestamps. callback
has 1 parameter: < Error >err.
-
fchown(< Buffer >handle, < integer >uid, < integer >gid, < function >callback) - (void) - Sets the owner for the resource associated with handle
. callback
has 1 parameter: < Error >err.
-
fchmod(< Buffer >handle, < mixed >mode, < function >callback) - (void) - Sets the mode for the resource associated with handle
. mode
can be an integer or a string containing an octal number. callback
has 1 parameter: < Error >err.
-
opendir(< string >path, < function >callback) - (void) - Opens a directory path
. callback
has 2 parameters: < Error >err, < Buffer >handle.
-
readdir(< Buffer >handle, < function >callback) - (void) - Retrieves directory entries from the directory associated with handle
. This function may need to be called multiple times to receive the entire directory listing. callback
has 2 parameters: < Error >err, < mixed >list. list
is either an Array of { filename: 'foo', longname: '....', attrs: {...} }
style objects (attrs is of type ATTR) OR boolean false to indicate no more directory entries are available for the given handle
.
-
unlink(< string >path, < function >callback) - (void) - Removes the file/symlink at path
. callback
has 1 parameter: < Error >err.
-
rename(< string >srcPath, < string >destPath, < function >callback) - (void) - Renames/moves srcPath
to destPath
. callback
has 1 parameter: < Error >err.
-
mkdir(< string >path, [< ATTRS >attributes, ]< function >callback) - (void) - Creates a new directory path
. callback
has 1 parameter: < Error >err.
-
rmdir(< string >path, < function >callback) - (void) - Removes the directory at path
. callback
has 1 parameter: < Error >err.
-
stat(< string >path, < function >callback) - (void) - Retrieves attributes for path
. callback
has 2 parameter: < Error >err, < Stats >stats.
-
lstat(< string >path, < function >callback) - (void) - Retrieves attributes for path
. If path
is a symlink, the link itself is stat'ed instead of the resource it refers to. callback
has 2 parameters: < Error >err, < Stats >stats.
-
setstat(< string >path, < ATTRS >attributes, < function >callback) - (void) - Sets the attributes defined in attributes
for path
. callback
has 1 parameter: < Error >err.
-
utimes(< string >path, < mixed >atime, < mixed >mtime, < function >callback) - (void) - Sets the access time and modified time for path
. atime
and mtime
can be Date instances or UNIX timestamps. callback
has 1 parameter: < Error >err.
-
chown(< string >path, < integer >uid, < integer >gid, < function >callback) - (void) - Sets the owner for path
. callback
has 1 parameter: < Error >err.
-
chmod(< string >path, < mixed >mode, < function >callback) - (void) - Sets the mode for path
. mode
can be an integer or a string containing an octal number. callback
has 1 parameter: < Error >err.
-
readlink(< string >path, < function >callback) - (void) - Retrieves the target for a symlink at path
. callback
has 2 parameters: < Error >err, < string >target.
-
symlink(< string >targetPath, < string >linkPath, < function >callback) - (void) - Creates a symlink at linkPath
to targetPath
. callback
has 1 parameter: < Error >err.
-
realpath(< string >path, < function >callback) - (void) - Resolves path
to an absolute path. callback
has 2 parameters: < Error >err, < string >absPath.
ATTRS
An object with the following valid properties:
-
mode - < integer > - Mode/permissions for the resource.
-
uid - < integer > - User ID of the resource.
-
gid - < integer > - Group ID of the resource.
-
size - < integer > - Resource size in bytes.
-
atime - < integer > - UNIX timestamp of the access time of the resource.
-
mtime - < integer > - UNIX timestamp of the modified time of the resource.
When supplying an ATTRS object to one of the SFTP methods:
Stats
An object with the same attributes as an ATTRS object with the addition of the following methods:
Pseudo-TTY settings
-
rows - < integer > - Number of rows (defaults to 24)
-
cols - < integer > - Number of columns (defaults to 80)
-
height - < integer > - Height in pixels (defaults to 480)
-
width - < integer > - Width in pixels (defaults to 640)
-
term - < string > - The value to use for $TERM (defaults to 'vt100')
rows
and cols
override width
and height
when rows
and cols
are non-zero.
Pixel dimensions refer to the drawable area of the window.
Zero dimension parameters are ignored.