SSH2 client and server modules written in pure JavaScript for node.js
ssh2. You are probably looking for documentation for
ssh2v0.8.x here
SSH2 client and server modules written in pure JavaScript for node.js.
Development/testing is done against OpenSSH (8.0 currently).
socksv5)
cpu-featuresis set as an optional package dependency (you do not need to install it explicitly/separately from
ssh2) that will be automatically built and used if possible. See the project's documentation for its own requirements.
npm install ssh2
const { readFileSync } = require('fs');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: readFileSync('/path/to/my/key') });
// example output: // Client :: ready // STDOUT: 17:41:15 up 22 days, 18:09, 1 user, load average: 0.00, 0.01, 0.05 // // Stream :: exit :: code: 0, signal: undefined // Stream :: close
const { readFileSync } = require('fs');const { Client } = require('ssh2');
const conn = new Client(); conn.on('ready', () => { console.log('Client :: ready'); conn.shell((err, stream) => { if (err) throw err; stream.on('close', () => { console.log('Stream :: close'); conn.end(); }).on('data', (data) => { console.log('OUTPUT: ' + data); }); stream.end('ls -l\nexit\n'); }); }).connect({ host: '192.168.100.100', port: 22, username: 'frylock', privateKey: readFileSync('/path/to/my/key') });
// example output: // Client :: ready // STDOUT: Last login: Sun Jun 15 09:37:21 2014 from 192.168.100.100 // // STDOUT: ls -l // exit // // STDOUT: [email protected]:
$ ls -l // // STDOUT: total 8 // // STDOUT: drwxr-xr-x 2 frylock frylock 4096 Nov 18 2012 mydir // // STDOUT: -rw-r--r-- 1 frylock frylock 25 Apr 11 2013 test.txt // // STDOUT: [email protected]:$ exit // // STDOUT: logout // // Stream :: close
const { Client } = require('ssh2');const conn = new Client(); conn.on('ready', () => { console.log('Client :: ready'); conn.forwardOut('192.168.100.102', 8000, '127.0.0.1', 80, (err, stream) => { if (err) throw err; stream.on('close', () => { console.log('TCP :: CLOSED'); conn.end(); }).on('data', (data) => { console.log('TCP :: DATA: ' + data); }).end([ 'HEAD / HTTP/1.1', 'User-Agent: curl/7.27.0', 'Host: 127.0.0.1', 'Accept: /', 'Connection: close', '', '' ].join('\r\n')); }); }).connect({ host: '192.168.100.100', port: 22, username: 'frylock', password: 'nodejsrules' });
// example output: // Client :: ready // TCP :: DATA: HTTP/1.1 200 OK // Date: Thu, 15 Nov 2012 13:52:58 GMT // Server: Apache/2.2.22 (Ubuntu) // X-Powered-By: PHP/5.4.6-1ubuntu1 // Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT // Content-Encoding: gzip // Vary: Accept-Encoding // Connection: close // Content-Type: text/html; charset=UTF-8 // // // TCP :: CLOSED
const { Client } = require('ssh2');const conn = new Client(); conn.on('ready', () => { console.log('Client :: ready'); conn.forwardIn('127.0.0.1', 8000, (err) => { if (err) throw err; console.log('Listening for connections on server on port 8000!'); }); }).on('tcp connection', (info, accept, reject) => { console.log('TCP :: INCOMING CONNECTION:'); console.dir(info); accept().on('close', () => { console.log('TCP :: CLOSED'); }).on('data', (data) => { console.log('TCP :: DATA: ' + data); }).end([ 'HTTP/1.1 404 Not Found', 'Date: Thu, 15 Nov 2012 02:07:58 GMT', 'Server: ForwardedConnection', 'Content-Length: 0', 'Connection: close', '', '' ].join('\r\n')); }).connect({ host: '192.168.100.100', port: 22, username: 'frylock', password: 'nodejsrules' });
// example output: // Client :: ready // Listening for connections on server on port 8000! // (.... then from another terminal on the server:
curl -I http://127.0.0.1:8000
) // TCP :: INCOMING CONNECTION: { destIP: '127.0.0.1', // destPort: 8000, // srcIP: '127.0.0.1', // srcPort: 41969 } // TCP DATA: HEAD / HTTP/1.1 // User-Agent: curl/7.27.0 // Host: 127.0.0.1:8000 // Accept: / // // // TCP :: CLOSED
const { Client } = require('ssh2');const conn = new Client(); conn.on('ready', () => { console.log('Client :: ready'); conn.sftp((err, sftp) => { if (err) throw err; sftp.readdir('foo', (err, list) => { if (err) throw err; console.dir(list); conn.end(); }); }); }).connect({ host: '192.168.100.100', port: 22, username: 'frylock', password: 'nodejsrules' });
// example output: // Client :: ready // [ { filename: 'test.txt', // longname: '-rw-r--r-- 1 frylock frylock 12 Nov 18 11:05 test.txt', // attrs: // { size: 12, // uid: 1000, // gid: 1000, // mode: 33188, // atime: 1353254750, // mtime: 1353254744 } }, // { filename: 'mydir', // longname: 'drwxr-xr-x 2 frylock frylock 4096 Nov 18 15:03 mydir', // attrs: // { size: 1048576, // uid: 1000, // gid: 1000, // mode: 16877, // atime: 1353269007, // mtime: 1353269007 } } ]
const { Client } = require('ssh2');const conn1 = new Client(); const conn2 = new Client();
// Checks uptime on 10.1.1.40 via 192.168.1.1
conn1.on('ready', () => { console.log('FIRST :: connection ready'); // Alternatively, you could use something like netcat or socat with exec() // instead of forwardOut(), depending on what the server allows conn1.forwardOut('127.0.0.1', 12345, '10.1.1.40', 22, (err, stream) => { if (err) { console.log('FIRST :: forwardOut error: ' + err); return conn1.end(); } conn2.connect({ sock: stream, username: 'user2', password: 'password2', }); }); }).connect({ host: '192.168.1.1', username: 'user1', password: 'password1', });
conn2.on('ready', () => { // This connection is the one to 10.1.1.40
console.log('SECOND :: connection ready'); conn2.exec('uptime', (err, stream) => { if (err) { console.log('SECOND :: exec error: ' + err); return conn1.end(); } stream.on('close', () => { conn1.end(); // close parent (and this) connection }).on('data', (data) => { console.log(data.toString()); }); }); });
const { Socket } = require('net');const { Client } = require('ssh2');
const conn = new Client();
conn.on('x11', (info, accept, reject) => { const xserversock = new net.Socket(); xserversock.on('connect', () => { const xclientsock = accept(); xclientsock.pipe(xserversock).pipe(xclientsock); }); // connects to localhost:0.0 xserversock.connect(6000, 'localhost'); });
conn.on('ready', () => { conn.exec('xeyes', { x11: true }, (err, stream) => { if (err) throw err; let code = 0; stream.on('close', () => { if (code !== 0) console.log('Do you have X11 forwarding enabled on your SSH server?'); conn.end(); }).on('exit', (exitcode) => { code = exitcode; }); }); }).connect({ host: '192.168.1.1', username: 'foo', password: 'bar' });
const socks = require('socksv5'); const { Client } = require('ssh2');const sshConfig = { host: '192.168.100.1', port: 22, username: 'nodejs', password: 'rules' };
socks.createServer((info, accept, deny) => { // NOTE: you could just use one ssh2 client connection for all forwards, but // you could run into server-imposed limits if you have too many forwards open // at any given time const conn = new Client(); conn.on('ready', () => { conn.forwardOut(info.srcAddr, info.srcPort, info.dstAddr, info.dstPort, (err, stream) => { if (err) { conn.end(); return deny(); }
const clientSocket = accept(true); if (clientSocket) { stream.pipe(clientSocket).pipe(stream).on('close', () => { conn.end(); }); } else { conn.end(); } });
}).on('error', (err) => { deny(); }).connect(sshConfig); }).listen(1080, 'localhost', () => { console.log('SOCKSv5 proxy server started on port 1080'); }).useAuth(socks.auth.None());
// test with cURL: // curl -i --socks5 localhost:1080 google.com
const http = require('http');const { Client, HTTPAgent, HTTPSAgent } = require('ssh2');
const sshConfig = { host: '192.168.100.1', port: 22, username: 'nodejs', password: 'rules' };
// Use
HTTPSAgent
instead for an HTTPS request const agent = new HTTPAgent(sshConfig); http.get({ host: '192.168.200.1', agent, headers: { Connection: 'close' } }, (res) => { console.log(res.statusCode); console.dir(res.headers); res.resume(); });
const { Client } = require('ssh2');const 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>]]>]]>
;const conn = new Client();
conn.on('ready', () => { console.log('Client :: ready'); conn.subsys('netconf', (err, stream) => { if (err) throw err; stream.on('data', (data) => { console.log(data); }).write(xmlhello); }); }).connect({ host: '1.2.3.4', port: 22, username: 'blargh', password: 'honk' });
const { timingSafeEqual } = require('crypto'); const { readFileSync } = require('fs'); const { inspect } = require('util');const { parseKey, Server } = require('ssh2');
const allowedUser = Buffer.from('foo'); const allowedPassword = Buffer.from('bar'); const allowedPubKey = parseKey(readFileSync('foo.pub'));
function checkValue(input, allowed) { const autoReject = (input.length !== allowed.length); if (autoReject) { // Prevent leaking length information by always making a comparison with the // same input when lengths don't match what we expect ... allowed = input; } const isMatch = timingSafeEqual(input, allowed); return (!autoReject && isMatch); }
new Server({ hostKeys: [readFileSync('host.key')] }, (client) => { console.log('Client connected!');
client.on('authentication', (ctx) => { let allowed = true; if (!checkValue(Buffer.from(ctx.username), allowedUser)) allowed = false;
switch (ctx.method) { case 'password': if (!checkValue(Buffer.from(ctx.password), allowedPassword)) return ctx.reject(); break; case 'publickey': if (ctx.key.algo !== allowedPubKey.type || !checkValue(ctx.key.data, allowedPubKey.getPublicSSH()) || (ctx.signature && allowedPubKey.verify(ctx.blob, ctx.signature) !== true)) { return ctx.reject(); } break; default: return ctx.reject(); } if (allowed) ctx.accept(); else ctx.reject();
}).on('ready', () => { console.log('Client authenticated!');
client.on('session', (accept, reject) => { const session = accept(); session.once('exec', (accept, reject, info) => { console.log('Client wants to execute: ' + inspect(info.command)); const stream = accept(); stream.stderr.write('Oh no, the dreaded errors!\n'); stream.write('Just kidding about the errors!\n'); stream.exit(0); stream.end(); }); });
}).on('close', () => { console.log('Client disconnected'); }); }).listen(0, '127.0.0.1', function() { console.log('Listening on port ' + this.address().port); });
const { timingSafeEqual } = require('crypto'); const { readFileSync } = require('fs'); const { inspect } = require('util');const { Server, sftp: { OPEN_MODE, STATUS_CODE, }, } = require('ssh2');
const allowedUser = Buffer.from('foo'); const allowedPassword = Buffer.from('bar');
function checkValue(input, allowed) { const autoReject = (input.length !== allowed.length); if (autoReject) { // Prevent leaking length information by always making a comparison with the // same input when lengths don't match what we expect ... allowed = input; } const isMatch = timingSafeEqual(input, allowed); return (!autoReject && isMatch); }
// This simple SFTP server implements file uploading where the contents get // ignored ...
new ssh2.Server({ hostKeys: [readFileSync('host.key')] }, (client) => { console.log('Client connected!');
client.on('authentication', (ctx) => { let allowed = true; if (!checkValue(Buffer.from(ctx.username), allowedUser)) allowed = false;
switch (ctx.method) { case 'password': if (!checkValue(Buffer.from(ctx.password), allowedPassword)) return ctx.reject(); break; default: return ctx.reject(); } if (allowed) ctx.accept(); else ctx.reject();
}).on('ready', () => { console.log('Client authenticated!');
client.on('session', (accept, reject) => { const session = accept(); session.on('sftp', (accept, reject) => { console.log('Client SFTP session'); const openFiles = new Map(); let handleCount = 0; const sftp = accept(); sftp.on('OPEN', (reqid, filename, flags, attrs) => { // Only allow opening /tmp/foo.txt for writing if (filename !== '/tmp/foo.txt' || !(flags & OPEN_MODE.WRITE)) return sftp.status(reqid, STATUS_CODE.FAILURE); // Create a fake handle to return to the client, this could easily // be a real file descriptor number for example if actually opening // a file on disk const handle = Buffer.alloc(4); openFiles.set(handleCount, true); handle.writeUInt32BE(handleCount++, 0); console.log('Opening file for write') sftp.handle(reqid, handle); }).on('WRITE', (reqid, handle, offset, data) => { if (handle.length !== 4 || !openFiles.has(handle.readUInt32BE(0))) { return sftp.status(reqid, STATUS_CODE.FAILURE); } // Fake the write operation sftp.status(reqid, STATUS_CODE.OK); console.log('Write to file at offset ${offset}: ${inspect(data)}'); }).on('CLOSE', (reqid, handle) => { let fnum; if (handle.length !== 4 || !openFiles.has(fnum = handle.readUInt32BE(0))) { return sftp.status(reqid, STATUS_CODE.FAILURE); } console.log('Closing file'); openFiles.delete(fnum); sftp.status(reqid, STATUS_CODE.OK); }); }); });
}).on('close', () => { console.log('Client disconnected'); }); }).listen(0, '127.0.0.1', function() { console.log('Listening on port ' + this.address().port); });
You can find more examples in the
examplesdirectory of this repository.
require('ssh2').Clientreturns the Client constructor.
require('ssh2').Serverreturns the Server constructor.
require('ssh2').utilsreturns an object containing some useful utilities.
require('ssh2').HTTPAgentreturns an
http.Agentconstructor.
require('ssh2').HTTPSAgentreturns an
https.Agentconstructor. Its API is the same as
HTTPAgentexcept it's for HTTPS connections.
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
acceptaccepts the connection and returns a
Channelobject. Calling
rejectrejects the connection and no further action is needed.
detailscontains:
forwardIn()).
forwardIn()).
x11(< object >details, < function >accept, < function >reject) - An incoming X11 connection is being requested. Calling
acceptaccepts the connection and returns a
Channelobject. Calling
rejectrejects the connection and no further action is needed.
detailscontains:
keyboard-interactive(< string >name, < string >instructions, < string >instructionsLang, < array >prompts, < function >finish) - The server is asking for replies to the given
promptsfor keyboard-interactive user authentication.
nameis generally what you'd use as a window title (for GUI apps).
promptsis an array of
{ prompt: 'Password: ', echo: false }style objects (here
echoindicates 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
finishwhen you are ready to continue. Note: It's possible for the server to come back and ask more questions.
unix connection(< object >details, < function >accept, < function >reject) - An incoming forwarded UNIX socket connection is being requested. Calling
acceptaccepts the connection and returns a
Channelobject. Calling
rejectrejects the connection and no further action is needed.
detailscontains:
change password(< string >prompt, < function >done) - If using password-based user authentication, the server has requested that the user's password be changed. Call
donewith the new password.
handshake(< object >negotiated) - Emitted when a handshake has completed (either initial or rekey).
negotiatedcontains the negotiated details of the handshake and is of the form:
// In this particular case `mac` is empty because there is no separate MAC // because it's integrated into AES in GCM mode { kex: 'ecdh-sha2-nistp256', srvHostKey: 'rsa-sha2-512', cs: { // Client to server algorithms cipher: 'aes128-gcm', mac: '', compress: 'none', lang: '' }, sc: { // Server to client algorithms cipher: 'aes128-gcm', mac: '', compress: 'none', lang: '' } }
rekey() - Emitted when a rekeying operation has completed (either client or server-initiated).
error(< Error >err) - An error occurred. A 'level' property indicates 'client-socket' for socket-level errors and 'client-ssh' for SSH disconnection messages. In the case of 'client-ssh' messages, there may be a 'description' property that provides more detail.
end() - The socket was disconnected.
close() - The socket was closed.
(constructor)() - Creates and returns a new Client instance.
connect(< object >config) - (void) - Attempts a connection to a server using the information given in
config:
'localhost'
22
host. Default:
false
host. Default:
false
(hashedKey[, callback])where
hashedKeyis a string hex hash of the host's key for verification purposes. Return
trueto continue with the handshake or
falseto reject and disconnect, or call
callback()with
trueor
falseif you need to perform asynchronous verification. Default: (auto-accept if
hostVerifieris not set)
trueto use OpenSSH agent forwarding (
[email protected]) for the life of the connection.
agentmust also be set to use this feature. Default:
false
true, you need to handle the
keyboard-interactiveevent. Default:
false
(methodsLeft, partialSuccess, callback)where
methodsLeftand
partialSuccessare
nullon the first authentication attempt, otherwise are an array and boolean respectively. Return or call
callback()with the name of the authentication method to try next (pass
falseto signal no more methods to try). Valid method names are:
'none', 'password', 'publickey', 'agent', 'keyboard-interactive', 'hostbased'. Default: function that follows a set method order: None -> Password -> Private Key -> Agent (-> keyboard-interactive if
tryKeyboardis
true) -> Hostbased
0
3
20000
openssh_noMoreSessions()) Default:
true
algorithms - object - This option allows you to explicitly override the default transport layer algorithms used for the connection. The value for each category must either be an array of valid algorithm names to set an exact list (with the most preferrable first) or an object containing
append,
prepend, and/or
removeproperties that each contain an array of algorithm names or RegExps to match to adjust default lists for each category. Valid keys:
curve25519-sha256 (node v14.0.0+)
[email protected] (node v14.0.0+)
ecdh-sha2-nistp256
ecdh-sha2-nistp384
ecdh-sha2-nistp521
diffie-hellman-group-exchange-sha256
diffie-hellman-group14-sha256
diffie-hellman-group15-sha512
diffie-hellman-group16-sha512
diffie-hellman-group17-sha512
diffie-hellman-group18-sha512
diffie-hellman-group-exchange-sha1
diffie-hellman-group14-sha1
diffie-hellman-group1-sha1
ssh-ed25519(node v12.0.0+)
ecdsa-sha2-nistp256
ecdsa-sha2-nistp384
ecdsa-sha2-nistp521
rsa-sha2-512
rsa-sha2-256
ssh-rsa
ssh-dss
[email protected](priority of chacha20-poly1305 may vary depending upon CPU and/or optional binding availability)
aes128-gcm
[email protected]
aes256-gcm
[email protected]
aes128-ctr
aes192-ctr
aes256-ctr
3des-cbc
aes256-cbc
aes192-cbc
aes128-cbc
arcfour256
arcfour128
arcfour
blowfish-cbc
cast128-cbc
[email protected]
[email protected]
[email protected]
hmac-sha2-256
hmac-sha2-512
hmac-sha1
hmac-md5
hmac-sha2-256-96
hmac-sha2-512-96
hmac-ripemd160
hmac-sha1-96
hmac-md5-96
none
[email protected]
zlib
debug - function - Set this to a function that receives a single string argument to get detailed (local) debug information. Default: (none)
exec(< string >command[, < object >options], < function >callback) - (void) - Executes
commandon the server.
callbackhas 2 parameters: < Error >err, < Channel >stream. Valid
optionsproperties are:
trueto 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
trueto use defaults below, set to a number to specify a specific screen number, or an object with the following valid properties:
false
0
'MIT-MAGIC-COOKIE-1'
shell([[< mixed >window,] < object >options]< function >callback) - (void) - Starts an interactive shell session on the server, with an optional
windowobject containing pseudo-tty settings (see 'Pseudo-TTY settings'). If
window === false, then no pseudo-tty is allocated.
optionssupports the
x11and
envoptions as described in
exec().
callbackhas 2 parameters: < Error >err, < Channel >stream.
forwardIn(< string >remoteAddr, < integer >remotePort, < function >callback) - (void) - Bind to
remoteAddron
remotePorton the server and forward incoming TCP connections.
callbackhas 2 parameters: < Error >err, < integer >port (
portis the assigned port number if
remotePortwas 0). Here are some special values for
remoteAddrand their associated binding behaviors:
unforwardIn(< string >remoteAddr, < integer >remotePort, < function >callback) - (void) - Unbind from
remoteAddron
remotePorton the server and stop forwarding incoming TCP connections. Until
callbackis called, more connections may still come in.
callbackhas 1 parameter: < Error >err.
forwardOut(< string >srcIP, < integer >srcPort, < string >dstIP, < integer >dstPort, < function >callback) - (void) - Open a connection with
srcIPand
srcPortas the originating address and port and
dstIPand
dstPortas the remote destination address and port.
callbackhas 2 parameters: < Error >err, < Channel >stream.
sftp(< function >callback) - (void) - Starts an SFTP session.
callbackhas 2 parameters: < Error >err, < SFTP >sftp. For methods available on
sftp, see the
SFTPclient documentation.
subsys(< string >subsystem, < function >callback) - (void) - Invokes
subsystemon the server.
callbackhas 2 parameters: < Error >err, < Channel >stream.
rekey([< function >callback]) - (void) - Initiates a rekey with the server. If
callbackis supplied, it is added as a one-time handler for the
rekeyevent.
end() - (void) - Disconnects the socket.
openssh_noMoreSessions(< function >callback) - (void) - OpenSSH extension that sends a request to reject any new sessions (e.g. exec, shell, sftp, subsys) for this connection.
callbackhas 1 parameter: < Error >err.
openssh_forwardInStreamLocal(< string >socketPath, < function >callback) - (void) - OpenSSH extension that binds to a UNIX domain socket at
socketPathon the server and forwards incoming connections.
callbackhas 1 parameter: < Error >err.
openssh_unforwardInStreamLocal(< string >socketPath, < function >callback) - (void) - OpenSSH extension that unbinds from a UNIX domain socket at
socketPathon the server and stops forwarding incoming connections.
callbackhas 1 parameter: < Error >err.
openssh_forwardOutStreamLocal(< string >socketPath, < function >callback) - (void) - OpenSSH extension that opens a connection to a UNIX domain socket at
socketPathon the server.
callbackhas 2 parameters: < Error >err, < Channel >stream.
connection(< Connection >client, < object >info) - A new client has connected.
infocontains the following properties:
remoteAddressof the connection.
remoteFamilyof the connection.
remotePortof the connection.
header - object - Information about the client's header:
versions - object - Various version information:
1.99or
2.0).
comments - string - Any text that comes after the software name/version.
Example: the identification string
SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2would be parsed as:
{ identRaw: 'SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2', version: { protocol: '2.0', software: 'OpenSSH_6.6.1p1' }, comments: 'Ubuntu-2ubuntu2' }
(constructor)(< object >config[, < function >connectionListener]) - Creates and returns a new Server instance. Server instances also have the same methods/properties/events as
net.Server.
connectionListenerif supplied, is added as a
connectionlistener. Valid
configproperties:
{ key: , passphrase: }for encrypted private keys. (Required) Default: (none)
algorithms - object - This option allows you to explicitly override the default transport layer algorithms used for incoming client connections. Each value must be an array of valid algorithms for that category. The order of the algorithms in the arrays are important, with the most favorable being first. For a list of valid and default algorithm names, please review the documentation for the version of
ssh2used by this module. Valid keys:
greeting - string - A message that is sent to clients immediately upon connection, before handshaking begins. Note: Most clients usually ignore this. Default: (none)
banner - string - A message that is sent to clients once, right before authentication begins. Default: (none)
ident - string - A custom server software name/version identifier. Default:
'ssh2js' + moduleVersion + 'srv'
highWaterMark - integer - This is the
highWaterMarkto use for the parser stream. Default:
32 * 1024
debug - function - Set this to a function that receives a single string argument to get detailed (local) debug information. Default: (none)
authentication(< AuthContext >ctx) - The client has requested authentication.
ctx.usernamecontains the client username,
ctx.methodcontains the requested authentication method, and
ctx.accept()and
ctx.reject([< Array >authMethodsLeft[, < Boolean >isPartialSuccess]])are used to accept or reject the authentication request respectively.
abortis emitted if the client aborts the authentication request. Other properties/methods available on
ctxdepends on the
ctx.methodof authentication the client has requested:
password:
callbackis called with
(newPassword), where
newPasswordis the new password supplied by the client. You may accept, reject, or prompt for another password change after
callbackis called.
keyboard-interactive:
promptsis an array of
{ prompt: 'Prompt text', echo: true }objects (
promptbeing the prompt text and
echoindicating whether the client's response to the prompt should be echoed to their display).
callbackis called with
(responses), where
responsesis an array of string responses matching up to the
prompts.
publickey:
key - object - Contains information about the public key sent by the client:
ssh-rsa).
blob - mixed - If the value is
undefined, the client is only checking the validity of the
key. If the value is a Buffer, then this contains the data to be verified that is passed to (along with the signature)
key.verify()where
keyis a public key parsed with
parseKey().
signature - mixed - If the value is
undefined, the client is only checking the validity of the
key. If the value is a Buffer, then this contains a signature to be verified that is passed to (along with the blob)
key.verify()where
keyis a public key parsed with
parseKey().
hostbased:
key - object - Contains information about the public key sent by the client:
ssh-rsa).
blob - Buffer - This contains the data to be verified that is passed to (along with the signature)
key.verify()where
keyis a public key parsed with
parseKey().
signature - Buffer - This contains a signature to be verified that is passed to (along with the blob)
key.verify()where
keyis a public key parsed with
parseKey().
localHostname - string - The local hostname provided by the client.
localUsername - string - The local username provided by the client.
ready() - Emitted when the client has been successfully authenticated.
session(< function >accept, < function >reject) - Emitted when the client has requested a new session. Sessions are used to start interactive shells, execute commands, request X11 forwarding, etc.
accept()returns a new Session instance.
tcpip(< function >accept, < function >reject, < object >info) - Emitted when the client has requested an outbound (TCP) connection.
accept()returns a new Channel instance representing the connection.
infocontains:
openssh.streamlocal(< function >accept, < function >reject, < object >info) - Emitted when the client has requested a connection to a UNIX domain socket.
accept()returns a new Channel instance representing the connection.
infocontains:
request(< mixed >accept, < mixed >reject, < string >name, < object >info) - Emitted when the client has sent a global request for
name(e.g.
tcpip-forwardor
cancel-tcpip-forward).
acceptand
rejectare functions if the client requested a response. If
bindPort === 0, you should pass the chosen port to
accept()so that the client will know what port was bound.
infocontains additional details about the request:
tcpip-forwardand
cancel-tcpip-forward:
[email protected]and
[email protected]:
handshake(< object >negotiated) - Emitted when a handshake has completed (either initial or rekey).
negotiatedcontains the negotiated details of the handshake and is of the form:
// In this particular case `mac` is empty because there is no separate MAC // because it's integrated into AES in GCM mode { kex: 'ecdh-sha2-nistp256', srvHostKey: 'rsa-sha2-512', cs: { // Client to server algorithms cipher: 'aes128-gcm', mac: '', compress: 'none', lang: '' }, sc: { // Server to client algorithms cipher: 'aes128-gcm', mac: '', compress: 'none', lang: '' } }
rekey() - Emitted when a rekeying operation has completed (either client or server-initiated).
error(< Error >err) - An error occurred.
end() - The client socket disconnected.
close() - The client socket was closed.
end() - (void) - Closes the client connection.
x11(< string >originAddr, < integer >originPort, < function >callback) - (void) - Alert the client of an incoming X11 client connection from
originAddron port
originPort.
callbackhas 2 parameters: < Error >err, < Channel >stream.
forwardOut(< string >boundAddr, < integer >boundPort, < string >remoteAddr, < integer >remotePort, < function >callback) - (void) - Alert the client of an incoming TCP connection on
boundAddron port
boundPortfrom
remoteAddron port
remotePort.
callbackhas 2 parameters: < Error >err, < Channel >stream.
openssh_forwardOutStreamLocal(< string >socketPath, < function >callback) - (void) - Alert the client of an incoming UNIX domain socket connection on
socketPath.
callbackhas 2 parameters: < Error >err, < Channel >stream.
rekey([< function >callback]) - (void) - Initiates a rekey with the client. If
callbackis supplied, it is added as a one-time handler for the
rekeyevent.
pty(< mixed >accept, < mixed >reject, < object >info) - The client requested allocation of a pseudo-TTY for this session.
acceptand
rejectare functions if the client requested a response.
infohas these properties:
window-change(< mixed >accept, < mixed >reject, < object >info) - The client reported a change in window dimensions during this session.
acceptand
rejectare functions if the client requested a response.
infohas these properties:
x11(< mixed >accept, < mixed >reject, < object >info) - The client requested X11 forwarding.
acceptand
rejectare functions if the client requested a response.
infohas these properties:
trueif only a single connection should be forwarded.
MIT-MAGIC-COOKIE-1).
env(< mixed >accept, < mixed >reject, < object >info) - The client requested an environment variable to be set for this session.
acceptand
rejectare functions if the client requested a response.
infohas these properties:
signal(< mixed >accept, < mixed >reject, < object >info) - The client has sent a signal.
acceptand
rejectare functions if the client requested a response.
infohas these properties:
SIGUSR1).
auth-agent(< mixed >accept, < mixed >reject) - The client has requested incoming ssh-agent requests be forwarded to them.
acceptand
rejectare functions if the client requested a response.
shell(< mixed >accept, < mixed >reject) - The client has requested an interactive shell.
acceptand
rejectare functions if the client requested a response.
accept()returns a Channel for the interactive shell.
exec(< mixed >accept, < mixed >reject, < object >info) - The client has requested execution of a command string.
acceptand
rejectare functions if the client requested a response.
accept()returns a Channel for the command execution.
infohas these properties:
sftp(< mixed >accept, < mixed >reject) - The client has requested the SFTP subsystem.
acceptand
rejectare functions if the client requested a response.
accept()returns an SFTP instance in server mode (see the
SFTPdocumentation for details).
infohas these properties:
subsystem(< mixed >accept, < mixed >reject, < object >info) - The client has requested an arbitrary subsystem.
acceptand
rejectare functions if the client requested a response.
accept()returns a Channel for the subsystem.
infohas these properties:
close() - The session was closed.
This is a normal streams2 Duplex Stream (used both by clients and servers), with the following changes:
A boolean property
allowHalfOpenexists and behaves similarly to the property of the same name for
net.Socket. When the stream's end() is called, if
allowHalfOpenis
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
true.
A
closeevent is emitted once the channel is completely closed on both the client and server.
Client-specific:
For exec():
exitevent may (the SSH2 spec says it is optional) be emitted when the process finishes. If the process finished normally, the process's return value is passed to the
exitcallback. If the process was interrupted by a signal, the following are passed to the
exitcallback: null, < string >signalName, < boolean >didCoreDump, < string >description.
exitevent, the
closeevent will be passed the same arguments for convenience.
stderrproperty contains a Readable stream that represents output from stderr.
For shell() and exec():
signal()doesn't work, try writing
'\x03'to the Channel stream instead.
Server-specific:
For exec-enabled channel instances there is an additional method available that may be called right before you close the channel. It has two different signatures:
For exec and shell-enabled channel instances,
channel.stderris a writable stream.
rows - < integer > - Number of rows. Default:
24
cols - < integer > - Number of columns. Default:
80
height - < integer > - Height in pixels. Default:
480
width - < integer > - Width in pixels. Default:
640
term - < string > - The value to use for $TERM. Default:
'vt100'
modes - < object > - An object containing Terminal Modes as keys, with each value set to each mode argument. Default:
null
rowsand
colsoverride
widthand
heightwhen
rowsand
colsare non-zero.
Pixel dimensions refer to the drawable area of the window.
Zero dimension parameters are ignored.
Name |
Description |
---|---|
VINTR | Interrupt character; 255 if none. Similarly for the other characters. Not all of these characters are supported on all systems. |
VQUIT | The quit character (sends SIGQUIT signal on POSIX systems). |
VERASE | Erase the character to left of the cursor. |
VKILL | Kill the current input line. |
VEOF | End-of-file character (sends EOF from the terminal). |
VEOL | End-of-line character in addition to carriage return and/or linefeed. |
VEOL2 | Additional end-of-line character. |
VSTART | Continues paused output (normally control-Q). |
VSTOP | Pauses output (normally control-S). |
VSUSP | Suspends the current program. |
VDSUSP | Another suspend character. |
VREPRINT | Reprints the current input line. |
VWERASE | Erases a word left of cursor. |
VLNEXT | Enter the next character typed literally, even if it is a special character |
VFLUSH | Character to flush output. |
VSWTCH | Switch to a different shell layer. |
VSTATUS | Prints system status line (load, command, pid, etc). |
VDISCARD | Toggles the flushing of terminal output. |
IGNPAR | The ignore parity flag. The parameter SHOULD be 0 if this flag is FALSE, and 1 if it is TRUE. |
PARMRK | Mark parity and framing errors. |
INPCK | Enable checking of parity errors. |
ISTRIP | Strip 8th bit off characters. |
INLCR | Map NL into CR on input. |
IGNCR | Ignore CR on input. |
ICRNL | Map CR to NL on input. |
IUCLC | Translate uppercase characters to lowercase. |
IXON | Enable output flow control. |
IXANY | Any char will restart after stop. |
IXOFF | Enable input flow control. |
IMAXBEL | Ring bell on input queue full. |
ISIG | Enable signals INTR, QUIT, [D]SUSP. |
ICANON | Canonicalize input lines. |
XCASE | Enable input and output of uppercase characters by preceding their lowercase equivalents with "". |
ECHO | Enable echoing. |
ECHOE | Visually erase chars. |
ECHOK | Kill character discards current line. |
ECHONL | Echo NL even if ECHO is off. |
NOFLSH | Don't flush after interrupt. |
TOSTOP | Stop background jobs from output. |
IEXTEN | Enable extensions. |
ECHOCTL | Echo control characters as ^(Char). |
ECHOKE | Visual erase for line kill. |
PENDIN | Retype pending input. |
OPOST | Enable output processing. |
OLCUC | Convert lowercase to uppercase. |
ONLCR | Map NL to CR-NL. |
OCRNL | Translate carriage return to newline (output). |
ONOCR | Translate newline to carriage return-newline (output). |
ONLRET | Newline performs a carriage return (output). |
CS7 | 7 bit mode. |
CS8 | 8 bit mode. |
PARENB | Parity enable. |
PARODD | Odd parity, else even. |
TTYOPISPEED | Specifies the input baud rate in bits per second. |
TTYOPOSPEED | Specifies the output baud rate in bits per second. |
http.Agentinstance used to tunnel an HTTP connection over SSH.
sshConfigis what is passed to
client.connect()and
agentOptionsis passed to the
http.Agentconstructor.
https.Agentinstance used to tunnel an HTTP connection over SSH.
sshConfigis what is passed to
client.connect()and
agentOptionsis passed to the
https.Agentconstructor.
parseKey(< mixed >keyData[, < string >passphrase]) - mixed - Parses a private/public key in OpenSSH, RFC4716, or PPK format. For encrypted private keys, the key will be decrypted with the given
passphrase.
keyDatacan be a Buffer or string value containing the key contents. The returned value will be an array of objects (currently in the case of modern OpenSSH keys) or an object with these properties and methods:
'ssh-rsa')
datausing this key and returns a Buffer containing the signature on success. On failure, an Error will be returned.
datacan be anything accepted by node's
sign.update().
signatureof the given
datausing this key and returns
trueif the signature could be verified. On failure, either
falsewill be returned or an Error will be returned upon a more critical failure.
datacan be anything accepted by node's
verify.update().
OPEN_MODE
STATUS_CODE
flagsToString()
stringToFlags()