ssh2-promise is a powerful promise wrapper around ssh2 client. It supports all the ssh2 client operation such as connection hopping, exec, spawn, shell, sftp, open tunnel, open socks connection etc... in promisify and async-await way. It helps in caching the sshconnection, to reduce time, during connection hopping. It have reconnect logic, so that, once disconnected, it can retry the sshconnection, automatically.
It has promise wrapper around sftp operations too.
This module is written in Typescript
. It can be used in Javascript
or in Typescript
with full type support.
We have upgraded to ssh2 v1.1.0. It means minimum Node requirement v10.16.0, if you need support for older version please use ssh2-promise v0.2.0
Change in sftp api, now ssh.sftp() provide wrapped SFTP session instead of raw sftp session.
//(Require Node v10.16.0 or newer)
npm install ssh2-promise;
//for older version (Supports for any version of Node)
npm install ssh2-promise@0.2.0
- docker
- docker-compose
cd pretest
docker-compose up -d
cd ..
yarn test
All examples are shown in promisify and async-await manner.
//in javascript manner
var SSH2Promise = require('ssh2-promise');
//or in typescript manner
import SSH2Promise = require('ssh2-promise');
//or in typescript manner (with esModuleInterop enabled)
import SSH2Promise from 'ssh2-promise';
//To import SFTP, SSHConfig, TunnelConfig Type definition, SSHConstants in typescript
//without esModuleInterop
import SFTP = require('ssh2-promise/lib/sftp')
import SSHConfig = require('ssh2-promise/lib/sshConfig');
import TunnelConfig = require('ssh2-promise/lib/tunnelConfig');
import SSHConstants = require('ssh2-promise/lib/sshConstants');
//with esModuleInterop
import SFTP from 'ssh2-promise/lib/sftp'
import SSHConfig from 'ssh2-promise/lib/sshConfig';
import TunnelConfig from 'ssh2-promise/lib/tunnelConfig';
import SSHConstants from 'ssh2-promise/lib/sshConstants';
Configuration passed to SSH2Promise is aligned to ssh2 library. For debugging, pass a debug function in configuration, similary how we do for SSH2
// The config passed to the Client constructor should match the config required by ssh2.
// Extra identity option is provided to directly pass the path of private key file
var sshconfig = {
host: '192.168.1.2',
username: 'ubuntu',
identity: '/here/is/my/key'
}
var ssh = new SSH2Promise(sshconfig);
//Promise
ssh.connect().then(() => {
console.log("Connection established")
});
//Async Await
(async function(){
await ssh.connect();
console.log("Connection established");
})();
//SSH server detail used for hopping
var sshconfig1 = {
host: '192.168.1.2',
username: 'ubuntu',
identity: '/here/is/my/key1'
}
//SSH server detail to be connected
var sshconfig2 = {
host: '192.168.1.3',
username: 'ubuntu',
password: 'mysecret2'
}
//It will establish connection to sshconfig2 via sshconfig1
//by default it will cache connection,
//to disable caching, pass second parameter as true
//new SSH2Promise([sshconfig1, sshconfig2], true)
var ssh = new SSH2Promise([sshconfig1, sshconfig2]);
//Promise
ssh.connect().then(() => {
console.log("Connection established")
});
//Async Await
(async function(){
await ssh.connect();
console.log("Connection established");
})();
var ssh = new SSH2Promise(sshconfig);
//Promise
//use exec, if output of command is limited
ssh.exec("whoami").then((data) => {
console.log(data); //ubuntu
});
//use spawn, if you want to stream on output of command
ssh.spawn("tail -f /var/log.txt").then((socket) => {
socket.on('data', () => {
//file content will be available here
})
});
//Async Await
//use exec, if output of command is limited
(async function(){
var data = await ssh.exec("whoami");
console.log(data); //ubuntu
})();
//use spawn, if you want to stream on output of command
(async function(){
var socket = await ssh.spawn("tail -f /var/log.txt");
socket.on('data', () => {
//file content will be available here
})
})();
var ssh = new SSH2Promise(sshconfig);
//Promise
//Get a sftp session
//see: https://github.com/mscdex/ssh2-streams/blob/master/SFTPStream.md
//in typescript import sftp type definition
//import SFTP = require('ssh2-promise/lib/sftp')
var sftp/*:SFTP*/ = ssh.sftp()
sftp.readdir("/").then((data) => {
console.log(data); //file listing
}).catch((err) => {
console.log(err);
})
//Get a shell session
ssh.shell().then((socket) => {
socket.on('data', () => {
//shell content will be available here
})
//Can write to socket
socket.write("")
});
//Async Await
//Get a sftp session
//see: https://github.com/mscdex/ssh2-streams/blob/master/SFTPStream.md
(async function(){
var sftp = ssh.sftp();
var data = await sftp.readdir("/")
console.log(data); //file listing
})();
//Get a shell session
(async function(){
var socket = await ssh.shell();
socket.on('data', () => {
//shell content will be available here
})
//Can write to socket
socket.write("")
})();
//in typescript import sftp type definition
//import SFTP = require('ssh2-promise/lib/sftp')
var ssh = new SSH2Promise(sshconfig);
var sftp/*:SFTP*/ = ssh.sftp(); //or new SSH2Promise.SFTP(ssh);
//We can do all sftp client operation listed in "https://github.com/mscdex/ssh2-streams/blob/master/SFTPStream.md" in promisify or async await manner.
//Promise
//Read dir
sftp.readdir("/").then((list) => {
console.log(list); //list of files in directory '/'
});
//Create ReadStream
sftp.createReadStream("/test.sh").then((stream) => {
console.log(stream); //Readable stream, which support data, close events etc..
});
//Get stat
sftp.getStat("/test.sh").then((stat) => {
console.log(stat); //Stat object
});
//Async Await
//Read dir
(async function(){
var list = await sftp.readdir("/");
console.log(list); //list of files in directory '/'
})();
//Create ReadStream
(async function(){
var stream = await sftp.createReadStream("/test.sh");
console.log(stream); //Readable stream, which support data, close events etc..
})();
//Get stat
(async function(){
var st = await sftp.getStat("/test.sh");
console.log(stat); //Stat object
})();
var ssh = new SSH2Promise(sshconfig);
//Promise
//It will establish the socks connection, one per ssh connection, and return the port
//It is mainly used for reverse tunneling
ssh.getSocksPort().then((port) => {
console.log(port); //Socks port
});
//Establish a forward tunneling to any resource over above server
ssh.addTunnel({remoteAddr: "www.google.com", remotePort: "80"}).then((tunnel) => {
console.log(tunnel.localPort); //Local port
});
//Async Await
//It will establish the socks connection, one per ssh connection, and return the port
//It is mainly used for reverse tunneling
(async function(){
var port = await ssh.getSocksPort();
console.log(port); //Socks port
})();
//Establish a forward tunneling to any resource over above server
(async function(){
var tunnel = await ssh.addTunnel({remoteAddr: "www.google.com", remotePort: "80"});
console.log(tunnel.localPort); //Local port
})();
var ssh = new SSH2Promise(sshconfig);
//It will establish the x11 forwarding, if
//x server running locally,
//x forwarding enabled on remote server
//xeyes command is installed on remote server
//Promise
ssh.x11('xeyes').then(() => {
console.log("success"); //if x server running locally, (x forwarding enabled & xeyes command is installed) on remote server
}, () => {
console.log("error"); //if any success condition is not met
});
//Async Await
(async function(){
try{
await ssh.x11('xeyes');
console.log("success"); //if x server running locally, (x forwarding enabled & xeyes command is installed) on remote server
}catch(err){
console.log("error"); //if any success condition is not met
}
})();
var ssh = new SSH2Promise(sshconfig);
//It will start subsystem
//Promise
ssh.subsys('sftp').then((stream) => {
console.log("success"); //sftp system started successfully
});
//Async Await
(async function(){
var stream = await ssh.subsys('sftp');
console.log("success"); //sftp system started successfully
})();
require('ssh2-promise')
require('ssh2-promise\lib\sftp')
-
ssh(< string >status, < object >sshconnection, < object >payload) - Event get generated, when sshconnection status get changed. Various status can be "beforeconnect", "connect", "beforedisconnect", "disconnect"
-
ssh:< status >(< object >sshconnection, < object >payload) - Event get generated, when sshconnection status is at particular status. Various status can be "beforeconnect", "connect", "beforedisconnect", "disconnect"
-
tunnel(< string >status, < object >sshconnection, < object >payload) - Event get generated, when tunnel status get changed. Various status can be "beforeconnect", "connect", "beforedisconnect", "disconnect"
-
tunnel:< status >(< object >sshconnection, < object >payload) - Event get generated, when tunnel status is at particular status. Various status can be "beforeconnect", "connect", "beforedisconnect", "disconnect"
-
(constructor)(< array >|< object >sshConfig, < (Promise) >disableCache) - Creates and returns a new SSH2Promise instance. Single or multiple sshconfigs can be passed. sshConfig passed to SSH2Promise is aligned to ssh2 library. It has few extra options other than ssh2 configuration.
-
host - string - Hostname or IP address of the server. Default:
'localhost'
-
port - integer - Port number of the server. Default:
22
-
forceIPv4 - (Promise) - Only connect via resolved IPv4 address for
host
. Default:false
-
forceIPv6 - (Promise) - Only connect via resolved IPv6 address for
host
. Default:false
-
hostHash - string - 'md5' or 'sha1'. The host's key is hashed using this method and passed to the hostVerifier function. Default: (none)
-
hostVerifier - function - Function with parameters
(hashedKey[, callback])
wherehashedKey
is a string hex hash of the host's key for verification purposes. Returntrue
to continue with the handshake orfalse
to reject and disconnect, or callcallback()
withtrue
orfalse
if you need to perform asynchronous verification. Default: (auto-accept ifhostVerifier
is not set) -
username - string - Username for authentication. Default: (none)
-
password - string - Password for password-based user authentication. Default: (none)
-
agent - string - Path to ssh-agent's UNIX socket for ssh-agent-based user authentication. Windows users: set to 'pageant' for authenticating with Pageant or (actual) path to a cygwin "UNIX socket." Default: (none)
-
agentForward - (Promise) - Set to
true
to use OpenSSH agent forwarding (auth-agent@openssh.com
) for the life of the connection.agent
must also be set to use this feature. Default:false
-
privateKey - mixed - Buffer or string that contains a private key for either key-based or hostbased user authentication (OpenSSH format). Default: (none)
-
passphrase - string - For an encrypted private key, this is the passphrase used to decrypt it. Default: (none)
-
localHostname - string - Along with localUsername and privateKey, set this to a non-empty string for hostbased user authentication. Default: (none)
-
localUsername - string - Along with localHostname and privateKey, set this to a non-empty string for hostbased user authentication. Default: (none)
-
tryKeyboard - (Promise) - Try keyboard-interactive user authentication if primary user authentication method fails. If you set this to
true
, you need to handle thekeyboard-interactive
event. Default:false
-
keepaliveInterval - integer - How often (in milliseconds) to send SSH-level keepalive packets to the server (in a similar way as OpenSSH's ServerAliveInterval config option). Set to 0 to disable. Default:
0
-
keepaliveCountMax - integer - How many consecutive, unanswered SSH-level keepalive packets that can be sent to the server before disconnection (similar to OpenSSH's ServerAliveCountMax config option). Default:
3
-
readyTimeout - integer - How long (in milliseconds) to wait for the SSH handshake to complete. Default:
20000
-
sock - ReadableStream - A ReadableStream to use for communicating with the server instead of creating and using a new TCP connection (useful for connection hopping).
-
strictVendor - (Promise) - Performs a strict server vendor check before sending vendor-specific requests, etc. (e.g. check for OpenSSH server when using
openssh_noMoreSessions()
) Default:true
-
algorithms - object - This option allows you to explicitly override the default transport layer algorithms used for the connection. 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
ssh2-streams
used by this module. Valid keys:-
kex - array - Key exchange algorithms.
-
cipher - array - Ciphers.
-
serverHostKey - array - Server host key formats.
-
hmac - array - (H)MAC algorithms.
-
compress - array - Compression algorithms.
-
-
compress - mixed - Set to
true
to enable compression if server supports it,'force'
to force compression (disconnecting if server does not support it), orfalse
to explicitly opt out of compression all of the time. Note: this setting is overridden when explicitly setting a compression algorithm in thealgorithms
configuration option. Default: (only use compression if that is only what the server supports) -
debug - function - Set this to a function that receives a single string argument to get detailed (local) debug information.
-
identity - to directly pass the path of private key file.
-
reconnect - to reconnect automatically, once disconnected. Default:
'true'
. -
reconnectTries - Number of reconnect tries. Default:
'10'
. -
reconnectDelay - Delay after which reconnect should be done. Default:
'5000'
. -
hoppingTool - To hop connection using this tool. Default:
'nc'
. Supported Tools are'nc'
,'socat'
,'native'
-
-
connect() - (Promise) - Try to establish a connection. No need to explicitly call connect method. It get called automatically, while doing operation.
-
exec(< string >cmd, < array >params, < objects >options) - (Promise) - Execute a cmd, return a result. Options are passed directly to ssh2 exec command.
-
spawn(< string >cmd, < array >params, < objects >options) - (Promise) - Spawn a cmd, return a stream. Options are passed directly to ssh2 exec command.
-
sftp() - (SFTP) - Get a new sftp session.
-
subsys(< string >subsystem) - (Promise) - Invoke a subsystem.
-
x11(< string >cmd) - (Promise) - Start a x11 forwarding, by invoking 'cmd' on remote server. It handles error scenario, such as if x11 command not installed on remote server, x11 forwarding not enabled on remote server, & x11 server not running locally, by rejecting it gracefully.
-
shell() - (Promise) - Get a shell session.
-
close() - (Promise) - Close the sshconnection and associated tunnels.
-
addTunnel(< object >tunnelConfig) - (Promise) - Establish a forward tunnel over ssh machine. TunnelConfig has following properties.
-
name - Unique name. Default:
'${remoteAddr}@${remotePort}'
-
remoteAddr - Remote Address to connect.
-
remotePort - Remote Port to connect.
-
localPort - Local port to bind to. By default, it will bind to a random port, if not passed.
-
-
getTunnel(< string >name) - Get a tunnel by name.
-
closeTunnel([< string >name]) - (Promise) - Close a tunnel, if name is passed. Otherwise, will close all the tunnels.
-
getSocksPort([< number >localPort]) - (Promise) - Start a socks server. And, return a socks port, for reverse tunneling purpose. localPort is optional. By default, it will bind to a random port, if not passed.
It supports all the sftp client operations, in promisify way. For detailed explanation of all the operation, please visit sftp. It has few extra methods getStat
, setStat
, changeTimestamp
, readFileData
, writeFileData
, changeMode
, changeOwner
.
-
(constructor)(< object > ssh2) - Creates and returns a new SFTP instance, which can perform all sftp client operation such readdir, mkdir etc... in promisify way.
-
fastGet(< string >remotePath, < string >localPath[, < object >options]) - (Promise) - Downloads a file at
remotePath
tolocalPath
using parallel reads for faster throughput.options
can have the following properties:-
concurrency - integer - Number of concurrent reads Default:
64
-
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
-
-
fastPut(< string >localPath, < string >remotePath[, < object >options]) - (Promise) - Uploads a file from
localPath
toremotePath
using parallel reads for faster throughput.options
can have the following properties:-
concurrency - integer - Number of concurrent reads Default:
64
-
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
-
mode - mixed - Integer or string representing the file mode to set for the uploaded file.
-
-
createReadStream(< string >path[, < object >options]) - (Promise) - if resolved successfully, returns a new readable stream for
path
.options
has the following defaults:{ flags: 'r', encoding: null, handle: null, mode: 0o666, autoClose: true }
options
can includestart
andend
values to read a range of bytes from the file instead of the entire file. Bothstart
andend
are inclusive and start at 0. Theencoding
can be'utf8'
,'ascii'
, or'base64'
.If
autoClose
is false, then the file handle won't be closed, even if there's an error. It is your responsiblity to close it and make sure there's no file handle leak. IfautoClose
is set to true (default behavior), onerror
orend
the file handle will be closed automatically.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]) - (Promise) - if resolved successfully, returns a new writable stream for
path
.options
has the following defaults:{ flags: 'w', encoding: null, mode: 0o666, autoClose: true }
options
may also include astart
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 >flags, [< mixed >attrs_mode]) - (Promise) - Opens a file
filename
withflags
with optional ATTRS object or file modeattrs_mode
.flags
is any of the flags supported byfs.open
(except sync flag). If promise resolved successfully, then return < Buffer >handle, otherwise < Error >err. -
close(< Buffer >handle) - (Promise) - Closes the resource associated with
handle
given by open() or opendir(). If promise is rejected, then return < Error >err. -
readFile(< string >path, [< string|object >encoding]) - (Promise) - Reads file content at given
path
. Defaultencoding
isnull
. If promise resolved successfully, then (if encoding is defined, then return < string >content otherwise return < buffer >content), otherwise < Error >err. -
writeFile(< string >path, < string >data, [< object >options]) - (Promise) - Writes
data
at givenpath
.options
can have two propertiesencoding
andflag
, Default encoding isutf8
, and flag isw
. If promise is rejected, then return < Error >err. -
readFileData(< string >filename, < Buffer >buffer, < integer >offset, < integer >length, < integer >position) - (Promise) - Reads
length
bytes from the resource associated withfile
starting atposition
and stores the bytes inbuffer
starting atoffset
. If promise resolved successfully, then return Array [< integer >bytesRead, < Buffer >buffer (offset adjusted), < integer >position], otherwise < Error >err. -
writeFileData(< string >filename, < integer >offset, < integer >length, < integer >position) - (Promise) - Writes
length
bytes frombuffer
starting atoffset
to the resource associated withfile
starting atposition
. If promise is rejected, then return < Error >err. -
getStat(< string >filename) - (Promise) - Retrieves attributes for the resource associated with
file
. If promise resolved successfully, then return < Stats >stats, otherwise < Error >err. -
setStat(< string >filename, < ATTRS >attributes) - (Promise) - Sets the attributes defined in
attributes
for the resource associated withfile
. If promise is rejected, then return < Error >err. -
changeTimestamp(< string >filename, < mixed >atime, < mixed >mtime) - (Promise) - Sets the access time and modified time for the resource associated with
file
.atime
andmtime
can be Date instances or UNIX timestamps. If promise is rejected, then return < Error >err. -
changeOwner(< string >filename, < integer >uid, < integer >gid) - (Promise) - Sets the owner for the resource associated with
file
. If promise is rejected, then return < Error >err. -
changeMode(< string >filename, < mixed >mode) - (Promise) - Sets the mode for the resource associated with
file
.mode
can be an integer or a string containing an octal number. If promise is rejected, then return < Error >err. -
opendir(< string >path) - (Promise) - Opens a directory
path
. If promise resolved successfully, then return < Buffer >handle, otherwise < Error >err. -
readdir(< mixed >location) - (Promise) - Retrieves a directory listing.
location
can either be a Buffer containing a valid directory handle from opendir() or a string containing the path to a directory. If promise resolved successfully, then return < mixed >list, otherwise < Error >err.list
is an Array of{ filename: 'foo', longname: '....', attrs: {...} }
style objects (attrs is of type ATTR). Iflocation
is a directory handle, this function may need to be called multiple times untillist
is boolean false, which indicates that no more directory entries are available for that directory handle. -
unlink(< string >path) - (Promise) - Removes the file/symlink at
path
. If promise is rejected, then return < Error >err. -
rename(< string >srcPath, < string >destPath) - (Promise) - Renames/moves
srcPath
todestPath
. If promise is rejected, then return < Error >err. -
mkdir(< string >path, [< ATTRS >attributes, ]) - (Promise) - Creates a new directory
path
. If promise is rejected, then return < Error >err. -
rmdir(< string >path) - (Promise) - Removes the directory at
path
. If promise is rejected, then return < Error >err. -
stat(< string >path) - (Promise) - Retrieves attributes for
path
. If promise resolved successfully, then return < Stats >stats, otherwise < Error >err. -
lstat(< string >path) - (Promise) - Retrieves attributes for
path
. Ifpath
is a symlink, the link itself is stat'ed instead of the resource it refers to. If promise resolved successfully, then return < Stats >stats, otherwise < Error >err. -
setstat(< string >path, < ATTRS >attributes) - (Promise) - Sets the attributes defined in
attributes
forpath
. If promise is rejected, then return < Error >err. -
utimes(< string >path, < mixed >atime, < mixed >mtime) - (Promise) - Sets the access time and modified time for
path
.atime
andmtime
can be Date instances or UNIX timestamps. If promise is rejected, then return < Error >err. -
chown(< string >path, < integer >uid, < integer >gid) - (Promise) - Sets the owner for
path
. If promise is rejected, then return < Error >err. -
chmod(< string >path, < mixed >mode) - (Promise) - Sets the mode for
path
.mode
can be an integer or a string containing an octal number. If promise is rejected, then return < Error >err. -
readlink(< string >path) - (Promise) - Retrieves the target for a symlink at
path
. If promise resolved successfully, then return < string >target, otherwise < Error >err. -
symlink(< string >targetPath, < string >linkPath) - (Promise) - Creates a symlink at
linkPath
totargetPath
. If promise is rejected, then return < Error >err. -
realpath(< string >path) - (Promise) - Resolves
path
to an absolute path. If promise resolved successfully, then return < string >absPath, otherwise < Error >err. -
ext_openssh_rename(< string >srcPath, < string >destPath) - (Promise) - OpenSSH extension Performs POSIX rename(3) from
srcPath
todestPath
. If promise is rejected, then return < Error >err. -
ext_openssh_statvfs(< string >path) - (Promise) - OpenSSH extension Performs POSIX statvfs(2) on
path
. If promise resolved successfully, then return < object >fsInfo, otherwise < Error >err.fsInfo
contains the information as found in the statvfs struct. -
ext_openssh_fstatvfs(< Buffer >handle) - (Promise) - OpenSSH extension Performs POSIX fstatvfs(2) on open handle
handle
. If promise resolved successfully, then return < object >fsInfo, otherwise < Error >err.fsInfo
contains the information as found in the statvfs struct. -
ext_openssh_hardlink(< string >targetPath, < string >linkPath) - (Promise) - OpenSSH extension Performs POSIX link(2) to create a hard link to
targetPath
atlinkPath
. If promise is rejected, then return < Error >err. -
ext_openssh_fsync(< Buffer >handle) - (Promise) - OpenSSH extension Performs POSIX fsync(3) on the open handle
handle
. If promise is rejected, then return < Error >err.
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:
-
atime
andmtime
can be either a Date instance or a UNIX timestamp. -
mode
can either be an integer or a string containing an octal number.
An object with the same attributes as an ATTRS object with the addition of the following methods:
-
stats.isDirectory()
-
stats.isFile()
-
stats.isBlockDevice()
-
stats.isCharacterDevice()
-
stats.isSymbolicLink()
-
stats.isFIFO()
-
stats.isSocket()
MIT