node-ssh
A promise-based SSH client for Node.js, built on ssh2. Run commands, transfer files and whole directories over SFTP, open shells and forward ports, with await instead of callbacks.
$ npm install node-sshExamples with recorded output
example.mjs
import { NodeSSH } from 'node-ssh'
const ssh = new NodeSSH()
await ssh.connect({
host: 'web-1.example.com',
username: 'deploy',
privateKeyPath: '/home/you/.ssh/id_ed25519',
})const deployed = await ssh.execCommand('git log -1 --oneline', { cwd: '~/site' })
console.log(deployed)
const missing = await ssh.execCommand('ls /srv/backups')
console.log(missing)ssh.dispose()Terminal
$ node example.mjs
execCommand resolves with the exit code, the signal and the trimmed output, also when the command fails, so check code. A cwd that starts with ~/ is relative to the remote user’s home directory (new in 14.0.0).
Each example ran with node-ssh 14.0.0 against OpenSSH 9.2 on Debian 12, and its output plays back at the speed it was recorded. The host name and key path in the code stand in for the test server’s.
What’s new in 14.0.0
14.0.0 requires Node.js 22 or later. These are the main changes; the changelog has all of them.
New options
timeout, signal, killSignalexec, execCommand- Stop a command after a number of milliseconds or when an
AbortSignalaborts. Timeouts noBufferexec, execCommand- Send output only to
onStdoutandonStderr. Without it, output too large for a string now rejects withERR_OUTPUT_TOO_LARGEinstead of crashing the process. Large output atomicputFile, putFiles, putDirectory- Upload to a temporary file and rename it into place, so readers never see a partial file. Atomic uploads
skipUnchangedputFile, putFiles, putDirectory- Skip files whose remote copy has the same size and modification time. Skipping unchanged files
Behaviour changes
- An error on an idle connection, such as
ECONNRESET, no longer crashes the process. #132 execandexecCommandreject when the connection fails during the command or a callback such asonStdoutthrows. They used to resolve withcode: null, or close the connection. #132 #257- With
cwd, the command no longer runs whencdfails, and a leading~is the remote user’s home directory. #443 - The CommonJS and ESM builds each have their own type declarations, which no longer need
esModuleInterop. TypeScript now rejectsimport NodeSSH from 'node-ssh'; import{ NodeSSH }by name. #444
Connect
connect(config) opens the connection and resolves with the NodeSSH instance once the server accepts the login. config is ssh2’s ConnectConfig, so options such as port, passphrase, agent, readyTimeout and keepaliveInterval go straight to ssh2. It needs a username, and a host or an existing sock.
import { NodeSSH } from 'node-ssh'
const ssh = new NodeSSH()
await ssh.connect({
host: 'web-1.example.com',
username: 'deploy',
privateKeyPath: '/home/you/.ssh/id_ed25519',
})node-ssh adds these options to ssh2’s:
privateKeyPathstring- Path of a private key file on this machine. node-ssh reads it before connecting. Don’t combine it with
privateKey. privateKeystring | Buffer- The key itself. Since 13.0.0 it no longer accepts a file path; since 14.0.0 it also accepts a
Buffer. passwordstring- Log in with a password.
tryKeyboardboolean- Also try keyboard-interactive authentication. With a
passwordand noonKeyboardInteractive, node-ssh answers a prompt that contains “password” with the password. Servers that only accept keyboard-interactive logins otherwise fail withAll configured authentication methods failed. onKeyboardInteractive(name, instructions, lang, prompts, finish) => void- Answer keyboard-interactive prompts yourself, by calling
finishwith one response per prompt. Used withtryKeyboard: true.
const password = process.env.DEPLOY_PASSWORD
await ssh.connect({
host: 'web-1.example.com',
username: 'deploy',
tryKeyboard: true,
onKeyboardInteractive(name, instructions, lang, prompts, finish) {
// One response per prompt
finish(prompts.map(() => password))
},
})onKeyboardInteractive is called only when the server offers keyboard-interactive authentication. OpenSSH offers it when KbdInteractiveAuthentication is yes in sshd_config; Debian and Ubuntu set it to no, and their servers still accept a password.
To log in another way after the server refuses one, check the error’s level and connect again, or pass ssh2’s authHandler option, which node-ssh passes on.
try {
await ssh.connect({ host: 'web-1.example.com', username: 'deploy', privateKeyPath: '/home/you/.ssh/id_ed25519' })
} catch (error) {
if (error.level !== 'client-authentication') throw error
// askForPassword: however your program asks
await ssh.connect({ host: 'web-1.example.com', username: 'deploy', password: await askForPassword() })
}isConnected() is true once the connection is ready, until it ends or closes.
Run commands
execCommand(command, options) runs a command in the remote user’s shell and resolves with stdout, stderr, code and signal when it exits. It resolves whatever the exit code, so check code. Output is trimmed unless you pass noTrim: true.
exec(command, parameters, options) escapes each parameter with shell-escape and appends it to the command. It resolves with stdout, and rejects with an error holding stderr if the command wrote anything to it, even with exit code 0. With stream: 'stderr' it resolves with stderr, and with stream: 'both' with the same object as execCommand.
const { stdout, stderr, code } = await ssh.execCommand('npm ci --omit=dev', { cwd: '~/site' })
if (code !== 0) {
throw new Error(`npm ci exited with code ${code}: ${stderr}`)
}
// Each parameter is escaped, so the spaces and parentheses reach ls as written
const listing = await ssh.exec('ls', ['-l', '/var/www/uploads/Q3 report (final).pdf'])
// stdin can be a string or a readable stream
await ssh.execCommand('cat > ~/site/.env', { stdin: 'PORT=3000\n' })// Resolves with stdout, and rejects if the command wrote anything to stderr
const branch = await ssh.exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: '~/site' })
// git fetch reports progress on stderr, so ask for both streams
const result = await ssh.exec('git', ['fetch', '--prune'], { cwd: '~/site', stream: 'both' })Options
cwdstring- Directory to run the command in. A leading
~is the remote user’s home directory. If the directory doesn’t exist, the command doesn’t run, and the result has the shell’s error instderrand a non-zerocode. stdinstring | Readable- Written to the command’s standard input, which is then closed. Without
stdin, it is closed right away. onStdout, onStderr(chunk: Buffer) => void- Called with each chunk as it arrives. If one throws, node-ssh closes the command’s channel and rejects with the error.
onChannel(channel: ClientChannel) => void- Called with ssh2’s channel once the server has started the command.
execOptionsExecOptions- Passed to ssh2’s
exec, for example{ pty: true }orenv. encodingBufferEncoding- How
stdoutandstderrare decoded.Default:'utf8' noTrimboolean- Keep leading and trailing whitespace, for example when reading a file’s exact contents.Default:
false noBufferboolean- Don’t collect output: it only goes to
onStdoutandonStderr, and the result’sstdoutandstderrare empty. Withexec, output on stderr then no longer rejects.Default:false timeoutnumber- Milliseconds, counted from the call, after which node-ssh stops the command and rejects. See timeouts.
signalAbortSignal- Stops the command and rejects with the signal’s reason when it aborts.
killSignalstring- What
timeoutandsignalask the server to send:ABRT,ALRM,FPE,HUP,ILL,INT,KILL,PIPE,QUIT,SEGV,TERM,USR1orUSR2, with or without theSIGprefix.Default:'TERM' stream'stdout' | 'stderr' | 'both'execonly: what it resolves with.Default:'stdout'
Prompts and pseudo-terminals
A program that asks questions reads the answers from its stdin. If it reads them without a terminal, pass all of them as stdin:
// ./setup.sh asks for a user name and a password
const result = await ssh.execCommand('./setup.sh', { stdin: 'alice\nsecret\n' })Some programs need a terminal: screen and tmux, and programs that only prompt on one. Without a terminal, a program may not print its prompts (bash’s read -p doesn’t) or may not ask at all; git clone of an HTTPS repository that needs a login fails with fatal: could not read Username. For those, pass pty: true through execOptions and write each answer once its prompt appears:
import { PassThrough } from 'node:stream'
const answers = [
['Username:', 'alice\n'],
['Password:', 'secret\n'],
]
const stdin = new PassThrough()
let output = ''
const result = await ssh.execCommand('./setup.sh', {
execOptions: { pty: true },
stdin,
onStdout(chunk) {
output += chunk
while (answers.length > 0 && output.includes(answers[0][0])) {
stdin.write(answers.shift()[1])
if (answers.length === 0) stdin.end()
}
},
})- The terminal is the program’s only output, so everything it writes arrives in
stdoutandstderrstays empty. Lines end in\r\n. - The terminal echoes what you write into
stdoutuntil the program turns echo off, so a password written before its prompt shows up instdout. - The end of
stdindoesn’t end the program, so an interactive shell started this way keeps running until it getsexit.
To run a full-screen program such as vim from a script, connected to your own terminal, see Interactive programs in the README.
OpenSSH runs the user’s login shell, from /etc/passwd on most systems, for every command and for requestShell; a SHELL variable in env doesn’t change that. To use another shell, run it as the command, such as 'ksh -l', and pass its commands as stdin. It exits at the end of its stdin.
Timeouts and stopping commands
When timeout passes, node-ssh asks the server to send killSignal to the command, closes the command’s channel and rejects with an SSHError whose code is ETIMEDOUT.
try {
const result = await ssh.execCommand('./build.sh', { cwd: '~/site', timeout: 5000 })
console.log(result.stdout)
} catch (error) {
if (error.code !== 'ETIMEDOUT') throw error
console.log('build.sh did not finish within 5 seconds')
}To stop a command yourself, pass an AbortSignal as signal. Aborting it does the same as the timeout, and the promise rejects with signal.reason. If the signal has already aborted, the promise rejects right away and the command doesn’t run.
const controller = new AbortController()
const tail = ssh.execCommand('tail -f /var/log/app/access.log', {
signal: controller.signal,
onStdout(chunk) {
process.stdout.write(chunk)
},
})
// later
controller.abort()
await tail.catch((error) => console.log(error.name)) // AbortErrorThe promise rejects as soon as the timeout passes or the signal aborts, without waiting for the command to exit. What happens to the command depends on the server:
- OpenSSH (tested with 9.2) sends the signal to the command’s process group, so programs the command started get it too. A command can catch or ignore the signal and keep running;
KILLcan’t be ignored. - Without a pseudo-terminal, closing the channel doesn’t stop the command on OpenSSH. With
execOptions: { pty: true }, OpenSSH also hangs up the terminal when the channel closes, which sendsSIGHUP. - OpenSSH refuses signal requests for forced commands (
command=inauthorized_keys), and other servers may ignore them. Without a pseudo-terminal, the command then keeps running.
ssh2’s own channel.signal(), on the channel from onChannel, sends nothing once the channel’s stdin has ended, which execCommand does right away when stdin is a string or not given. timeout and signal send the request in that case too. #422
Large output
execCommand keeps all output in memory and returns it as strings. If it’s too large for a string, the promise rejects with an SSHError whose code is ERR_OUTPUT_TOO_LARGE. With noBuffer: true, output only goes to your callbacks:
import fs from 'node:fs'
const file = fs.createWriteStream('./access.log')
await ssh.execCommand('cat /var/log/app/access.log', {
noBuffer: true,
onStdout(chunk) {
file.write(chunk)
},
})
file.end()Transfer files
File transfers use SFTP. Each method opens an SFTP session and closes it when done, unless you pass one in. The local path comes first, then the remote path, for uploads and downloads alike.
// Local path first, then remote path, in both directions
await ssh.putFile('./dist/index.html', '/var/www/site/index.html')
await ssh.getFile('./backups/app.db', '/var/lib/app/app.db')
await ssh.putFiles([
{ local: './dist/index.html', remote: '/var/www/site/index.html' },
{ local: './dist/assets/app.js', remote: '/var/www/site/assets/app.js' },
])- Both paths name the file itself: to upload into a directory, put the file name at the end of the remote path.
putFilecreates missing remote directories. putFilesuploadsconcurrencyfiles at a time (1 unless set) and rejects on the first failure. The error’stransferredproperty lists the files uploaded before it.transferOptionsgo to ssh2’sfastPutandfastGet:concurrency,chunkSize,step(progress) andmode.
Directories
putDirectory(local, remote, options) and getDirectory(local, remote, options) create the directories first, then transfer the files, concurrency at a time. A file that fails doesn’t reject the call: tick gets its error, and the call resolves with false instead of true. For getDirectory, the local directory must exist.
import path from 'node:path'
const failed = []
const ok = await ssh.putDirectory('./dist', '/var/www/site', {
concurrency: 4,
// Replaces the default, which leaves out names that start with a dot
validate: (itemPath) => !path.basename(itemPath).startsWith('.') && !itemPath.endsWith('.map'),
tick(localFile, remoteFile, error) {
if (error) failed.push(localFile)
},
})
console.log(ok ? 'uploaded everything' : `failed: ${failed.join(', ')}`)recursiveboolean- Include subdirectories.Default:
true concurrencynumber- Transfers at a time. Not every server handles many at once; 1 has worked with the widest range of servers.Default:
1 validate(path: string) => boolean- Called with the path of each file and directory, local for
putDirectoryand remote forgetDirectory; returnfalseto leave it out, with everything inside it. The default leaves out names that start with a dot. tick(localFile, remoteFile, error, skipped) => void- Called after each file, with the error or
null.putDirectoryalso passesskipped. atomic, skipUnchangedbooleanputDirectoryonly. See below.Default:falsesftp, transferOptionsSFTPWrapper, TransferOptions- An SFTP session to use, and the options for each file.
Atomic uploads
While a file uploads, its remote path holds an incomplete file, and a web server reading that path could serve part of it. With atomic: true, putFile, putFiles and putDirectory upload each file to a hidden temporary file in the same remote directory (.name.<random hex>.tmp) and rename it to the remote path once the upload is complete.
await ssh.putFile('./dist/index.html', '/var/www/site/index.html', null, null, { atomic: true })
await ssh.putDirectory('./dist', '/var/www/site', { atomic: true })When the server supports the posix-rename@openssh.com extension, as OpenSSH does, the rename replaces an existing file in one step. Otherwise node-ssh uses a plain SFTP rename, and if that fails, deletes the existing file and renames again; the remote path is missing for a moment, so this fallback is not atomic.
The renamed file is a new file, so it doesn’t keep the mode or owner of the file it replaces; pass transferOptions: { mode } to set its mode. Creating the temporary file needs write permission on the remote directory, not only on the file. If the upload or the rename fails, node-ssh deletes the temporary file before rejecting. If the connection drops, the temporary file can stay behind.
Skipping unchanged files
With skipUnchanged: true, putFile, putFiles and putDirectory look up each remote path first and skip the upload when it is a regular file with the same size and modification time as the local file. After an upload, they set the remote file’s access and modification times to the local file’s, so the next upload can skip it. The server’s clock doesn’t matter.
await ssh.putDirectory('./dist', '/var/www/site', {
skipUnchanged: true,
tick(localFile, remoteFile, error, skipped) {
if (error) {
console.log('failed', localFile)
} else if (skipped) {
console.log('unchanged', localFile)
} else {
console.log('uploaded', localFile)
}
},
})- SFTP sends times in whole seconds, so the local modification time is rounded down to a second. A file uploaded without
skipUnchangedhas the time of that upload, so the first upload with it uploads the file again. - The check doesn’t read file contents: a file that changed but kept its size and modification time is skipped. A skipped file keeps its remote mode and owner.
- If the server can’t set the times, for example on a file owned by another user, the upload rejects. Without
atomic, the remote file already has the new contents then.
Reusing an SFTP session
The file methods take an SFTP session as a parameter (putFile, getFile, mkdir) or as the sftp option. withSFTP opens one and ends it when the callback settles.
await ssh.withSFTP(async (sftp) => {
for (const name of ['index.html', 'about/index.html', 'assets/app.css']) {
await ssh.putFile(`./dist/${name}`, `/var/www/site/${name}`, sftp)
}
})Creating directories
mkdir(path) creates a remote directory and its missing parents over SFTP; with mkdir(path, 'exec') it runs mkdir -p instead. A directory that already exists is fine; a file at that path rejects.
// Creates /var/www/releases and /var/www/releases/42 if they are missing
await ssh.mkdir('/var/www/releases/42')Shells and SFTP sessions
requestShell(options) resolves with ssh2’s channel for an interactive shell. options go to ssh2’s shell(): pseudo-terminal settings such as rows, cols and term, or false for no pseudo-terminal. withShell(callback, options) passes the channel to callback and destroys it when the callback settles.
// false: no pseudo-terminal, so the output has no prompt or echo
await ssh.withShell(async (shell) => {
shell.end('cd ~/site && git log -1 --oneline\n')
for await (const chunk of shell) {
process.stdout.write(chunk)
}
}, false)requestSFTP() resolves with ssh2’s SFTPWrapper, whose methods take callbacks; withSFTP(callback) ends the session when the callback settles.
await ssh.withSFTP(async (sftp) => {
const entries = await new Promise((resolve, reject) => {
sftp.readdir('/var/www/site', (error, list) => (error ? reject(error) : resolve(list)))
})
console.log(entries.map((entry) => entry.filename))
})Port forwarding
forwardOut(srcIP, srcPort, dstIP, dstPort) resolves with a channel to dstIP:dstPort as seen from the server, like ssh -L. srcIP and srcPort tell the server where the connection comes from.
import net from 'node:net'
// Port 15432 on this machine reaches PostgreSQL on the server
const server = net.createServer(async (socket) => {
try {
const channel = await ssh.forwardOut('127.0.0.1', 0, '127.0.0.1', 5432)
socket.pipe(channel).pipe(socket)
} catch (error) {
socket.destroy(error)
}
})
server.listen(15432, '127.0.0.1')forwardIn(remoteAddr, remotePort, onConnection) asks the server to listen on remoteAddr:remotePort and calls onConnection for each connection, like ssh -R. Pass port 0 to let the server pick one. It resolves with the port and dispose(), which stops listening.
import net from 'node:net'
// Port 8080 on the server reaches port 3000 on this machine
const forward = await ssh.forwardIn('127.0.0.1', 8080, (details, accept) => {
const channel = accept()
const local = net.connect(3000, '127.0.0.1')
channel.pipe(local).pipe(channel)
})
// later
await forward.dispose()forwardOutStreamLocal(socketPath) and forwardInStreamLocal(socketPath, onConnection) do the same for Unix domain sockets on the server, using an OpenSSH extension.
Errors and disconnecting
- Invalid arguments throw an
AssertionErrorfromnode:assertwhose message names the argument, such asconfig.username must be a valid string. - Methods that need the connection throw
Not connected to serverbeforeconnect()and after the connection has ended. - node-ssh’s own errors are instances of
SSHError, with acode:ETIMEDOUTwhen a command’stimeoutpasses or when the connection closes before the login completes (with the messageNo response from server), andERR_OUTPUT_TOO_LARGEfor output too large to return as a string. - Other errors come from ssh2 and the server.
import { SSHError } from 'node-ssh'
try {
await ssh.execCommand('make release', { cwd: '~/site', timeout: 60_000 })
} catch (error) {
if (!(error instanceof SSHError) || error.code !== 'ETIMEDOUT') throw error
console.log('make release did not finish within a minute')
} finally {
ssh.dispose()
}An error on an idle connection, such as ECONNRESET or a keepalive timeout, marks it as disconnected: isConnected() returns false, and the next call throws Not connected to server. To see the error, listen on ssh2’s client:
ssh.connection.on('error', (error) => {
console.error('SSH connection error:', error.message)
})dispose() ends the connection. If SFTP close requests are still waiting for the server’s reply, it waits for them first, up to 2 seconds. It returns nothing.
TypeScript
node-ssh includes its type declarations: lib/index.d.ts for require and lib/index.d.mts for import. They use types from ssh2, so TypeScript projects also need @types/ssh2. It’s an optional peer dependency, which package managers don’t install for you. No other compiler options are needed.
Import NodeSSH by name. node-ssh has no default export, so TypeScript reports import NodeSSH from 'node-ssh' as an error.
npm install --save-dev @types/ssh2import { NodeSSH, type Config, type SSHExecCommandResponse } from 'node-ssh'
const config: Config = {
host: 'web-1.example.com',
username: 'deploy',
privateKeyPath: '/home/you/.ssh/id_ed25519',
}
const ssh = await new NodeSSH().connect(config)
const result: SSHExecCommandResponse = await ssh.execCommand('uptime')API reference
The package exports NodeSSH, SSHError and the types below. Methods of NodeSSH:
Connection
connect(config: Config): Promise<this>Opens the connection and resolves with the instance once the server accepts the login. Throws an AssertionError for invalid config. Guide
isConnected(): booleanWhether the connection is ready and hasn’t ended or closed.
dispose(): voidEnds the connection, after pending SFTP close replies or 2 seconds, whichever comes first. Guide
connection: Client | nullssh2’s Client while connected, otherwise null. For ssh2 features node-ssh doesn’t wrap, and for errors on an idle connection.
Commands
execCommand(command: string, options?: SSHExecCommandOptions): Promise<SSHExecCommandResponse>Runs command in the remote user’s shell and resolves with stdout, stderr, code and signal when it exits. Guide
exec(
command: string,
parameters: string[],
options?: SSHExecOptions & { stream?: 'stdout' | 'stderr' },
): Promise<string>
exec(
command: string,
parameters: string[],
options?: SSHExecOptions & { stream: 'both' },
): Promise<SSHExecCommandResponse>Escapes parameters and runs the command. Resolves with stdout and rejects if anything was written to stderr, unless stream says otherwise. Guide
Files
putFile(
localFile: string,
remoteFile: string,
sftp?: SFTPWrapper | null,
transferOptions?: TransferOptions | null,
options?: SSHPutFileOptions,
): Promise<void>Uploads a file and creates missing remote directories. options: atomic, skipUnchanged. Guide
putFiles(
files: { local: string; remote: string }[],
options?: SSHPutFilesOptions,
): Promise<void>Uploads files, concurrency at a time. Rejects on the first failure, with the files uploaded before it in error.transferred. Guide
putDirectory(
localDirectory: string,
remoteDirectory: string,
options?: SSHGetPutDirectoryOptions,
): Promise<boolean>Uploads a directory. Resolves with false if any file failed. Guide
getFile(
localFile: string,
remoteFile: string,
sftp?: SFTPWrapper | null,
transferOptions?: TransferOptions | null,
): Promise<void>Downloads a file. The local path comes first. Guide
getDirectory(
localDirectory: string,
remoteDirectory: string,
options?: SSHGetPutDirectoryOptions,
): Promise<boolean>Downloads a directory into an existing local directory. Resolves with false if any file failed. Ignores atomic and skipUnchanged. Guide
mkdir(path: string, method?: 'sftp' | 'exec', sftp?: SFTPWrapper | null): Promise<void>Creates a remote directory and its parents, over SFTP (the default) or with mkdir -p. Guide
Shells and SFTP sessions
requestShell(options?: PseudoTtyOptions | ShellOptions | false): Promise<ClientChannel>Opens an interactive shell. Guide
withShell(
callback: (channel: ClientChannel) => Promise<void>,
options?: PseudoTtyOptions | ShellOptions | false,
): Promise<void>Opens a shell, passes it to the callback and destroys it when the callback settles. Guide
requestSFTP(): Promise<SFTPWrapper>Opens an SFTP session. Guide
withSFTP(callback: (sftp: SFTPWrapper) => Promise<void>): Promise<void>Opens an SFTP session, passes it to the callback and ends it when the callback settles. Guide
Port forwarding
forwardIn(
remoteAddr: string,
remotePort: number,
onConnection?: SSHForwardInListener,
): Promise<SSHForwardInDetails>Listens on the server and calls onConnection for each connection. Resolves with port and dispose(). Guide
forwardOut(srcIP: string, srcPort: number, dstIP: string, dstPort: number): Promise<Channel>Opens a channel to dstIP:dstPort as seen from the server. Guide
forwardInStreamLocal(
socketPath: string,
onConnection?: SSHForwardInStreamLocalListener,
): Promise<SSHForwardInStreamLocalDetails>forwardIn for a Unix domain socket on the server. Resolves with dispose(). Guide
forwardOutStreamLocal(socketPath: string): Promise<Channel>forwardOut to a Unix domain socket on the server. Guide
Types
SSHError extends Error with code: string | null. The option and result types, in full:
Type declarations (146 lines)
// Types from other packages that the declarations below use
import {
AcceptConnection,
Channel,
Client,
ClientChannel,
ConnectConfig,
ExecOptions,
Prompt,
PseudoTtyOptions,
RejectConnection,
SFTPWrapper,
ShellOptions,
TcpConnectionDetails,
TransferOptions,
UNIXConnectionDetails,
} from 'ssh2'
import { Readable } from 'stream'
export type Config = ConnectConfig & {
password?: string
privateKey?: string | Buffer
privateKeyPath?: string
tryKeyboard?: boolean
onKeyboardInteractive?: (
name: string,
instructions: string,
lang: string,
prompts: Prompt[],
finish: (responses: string[]) => void,
) => void
}
export interface SSHExecCommandOptions {
// A leading ~ is the remote user's home directory
cwd?: string
stdin?: string | Readable
execOptions?: ExecOptions
encoding?: BufferEncoding
noTrim?: boolean
noBuffer?: boolean
timeout?: number
signal?: AbortSignal
killSignal?: string
onChannel?: (clientChannel: ClientChannel) => void
onStdout?: (chunk: Buffer) => void
onStderr?: (chunk: Buffer) => void
}
export interface SSHExecCommandResponse {
stdout: string
stderr: string
code: number | null
signal: string | null
}
export interface SSHExecOptions extends SSHExecCommandOptions {
stream?: 'stdout' | 'stderr' | 'both'
}
export interface SSHPutFileOptions {
atomic?: boolean
skipUnchanged?: boolean
}
export interface SSHPutFilesOptions extends SSHPutFileOptions {
sftp?: SFTPWrapper | null
concurrency?: number
transferOptions?: TransferOptions
}
export interface SSHGetPutDirectoryOptions extends SSHPutFilesOptions {
tick?: (localFile: string, remoteFile: string, error: Error | null, skipped?: boolean) => void
validate?: (path: string) => boolean
recursive?: boolean
}
export type SSHMkdirMethod = 'sftp' | 'exec'
export type SSHForwardInListener = (
details: TcpConnectionDetails,
accept: AcceptConnection<ClientChannel>,
reject: RejectConnection,
) => void
export interface SSHForwardInDetails {
dispose(): Promise<void>
port: number
}
export type SSHForwardInStreamLocalListener = (
info: UNIXConnectionDetails,
accept: AcceptConnection,
reject: RejectConnection,
) => void
export interface SSHForwardInStreamLocalDetails {
dispose(): Promise<void>
}
export class SSHError extends Error {
code: string | null
constructor(message: string, code?: string | null)
}
export class NodeSSH {
connection: Client | null
connect(config: Config): Promise<this>
isConnected(): boolean
requestShell(options?: PseudoTtyOptions | ShellOptions | false): Promise<ClientChannel>
withShell(
callback: (channel: ClientChannel) => Promise<void>,
options?: PseudoTtyOptions | ShellOptions | false,
): Promise<void>
requestSFTP(): Promise<SFTPWrapper>
withSFTP(callback: (sftp: SFTPWrapper) => Promise<void>): Promise<void>
execCommand(command: string, options?: SSHExecCommandOptions): Promise<SSHExecCommandResponse>
exec(
command: string,
parameters: string[],
options?: SSHExecOptions & {
stream?: 'stdout' | 'stderr'
},
): Promise<string>
exec(
command: string,
parameters: string[],
options?: SSHExecOptions & {
stream: 'both'
},
): Promise<SSHExecCommandResponse>
mkdir(path: string, method?: SSHMkdirMethod, sftp?: SFTPWrapper | null): Promise<void>
getFile(
localFile: string,
remoteFile: string,
sftp?: SFTPWrapper | null,
transferOptions?: TransferOptions | null,
): Promise<void>
putFile(
localFile: string,
remoteFile: string,
sftp?: SFTPWrapper | null,
transferOptions?: TransferOptions | null,
options?: SSHPutFileOptions,
): Promise<void>
putFiles(files: { local: string; remote: string }[], options?: SSHPutFilesOptions): Promise<void>
putDirectory(localDirectory: string, remoteDirectory: string, options?: SSHGetPutDirectoryOptions): Promise<boolean>
getDirectory(localDirectory: string, remoteDirectory: string, options?: SSHGetPutDirectoryOptions): Promise<boolean>
forwardIn(remoteAddr: string, remotePort: number, onConnection?: SSHForwardInListener): Promise<SSHForwardInDetails>
forwardOut(srcIP: string, srcPort: number, dstIP: string, dstPort: number): Promise<Channel>
forwardInStreamLocal(
socketPath: string,
onConnection?: SSHForwardInStreamLocalListener,
): Promise<SSHForwardInStreamLocalDetails>
forwardOutStreamLocal(socketPath: string): Promise<Channel>
dispose(): void
}