### Install Node-SSH Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Use npm or Yarn to install the node-ssh package. ```sh $ npm install node-ssh # If you're using npm $ yarn add node-ssh # If you're using Yarn ``` -------------------------------- ### Install TypeScript Dependencies Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Commands to install the required @types/ssh2 package for TypeScript support. ```bash yarn add --dev @types/ssh2 # OR npm install --save-dev @types/ssh2 ``` -------------------------------- ### Using SSHError with instanceof check Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Shows how to import SSHError and use it in a try-catch block to check if an error is an instance of SSHError, then access its code and message. The comment shows an example output: ETIMEDOUT: No response from server. ```JavaScript const { SSHError } = require('node-ssh') try { await ssh.connect({ host: '10.0.0.1', username: 'x', password: 'y' }) } catch (err) { if (err instanceof SSHError) { console.error(`failed with code ${err.code}: ${err.message}`) // ETIMEDOUT: No response from server } } ``` -------------------------------- ### Instantiate and connect with NodeSSH Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Demonstrates creating a new NodeSSH instance, connecting to a server, and disposing of the connection. ```javascript const { NodeSSH } = require('node-ssh') const ssh = new NodeSSH() await ssh.connect({ host: 'localhost', username: 'steel', password: 'password' }) // ... work ... ssh.dispose() ``` -------------------------------- ### mkdir(path: string, method?: SSHMkdirMethod = 'sftp', givenSftp?: SFTPWrapper | null = null): Promise Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Creates a directory tree on the remote server. Supports two methods: 'sftp' (default) and 'exec'. ```APIDOC ## mkdir(path: string, method?: SSHMkdirMethod = 'sftp', givenSftp?: SFTPWrapper | null = null): Promise ### Description Creates a directory tree on the remote. `method` is `'sftp'` (default) or `'exec'`. ### Parameters - **path** (string) - Required - The directory path to create. - **method** (SSHMkdirMethod) - Optional - The method to use: `'sftp'` or `'exec'`. Defaults to `'sftp'`. - **givenSftp** (SFTPWrapper | null) - Optional - An existing SFTP session to reuse. If not provided, a new session is created and closed after the operation. ### Behavior - **'exec'** — runs `mkdir -p ` via `exec`. - **'sftp'** — stats `path`; if it exists and is a directory, returns immediately; if it exists and is **not** a directory, rejects with `Error('mkdir() failed, target already exists and is not a directory')`. Otherwise `sftp.mkdir(path)`; if that fails with an error whose stack matches `/Error: (E[\S]+): /`, it rejects with `SSHError(err.message, extractedCode)` — codes such as `ENOTDIR`, `ENOENT`, `EEXIST` propagate. If the failure message is `'No such file'` or the code is `'ENOENT'`, it recurses into `mkdir(dirname(path), 'sftp', sftp)` to create parents and retries the leaf once. ### Return Type `Promise`\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\.\. ``` -------------------------------- ### Connect with private key Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Connects to a server using a private key file path. ```typescript const ssh = await new NodeSSH().connect({ host: 'localhost', port: 22, username: 'steel', privateKeyPath: '/home/steel/.ssh/id_rsa', }) ``` -------------------------------- ### Create remote directories with mkdir Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Creates a directory tree on the remote server using either SFTP or shell execution. ```ts await ssh.mkdir('/var/www/app/static', 'sftp') // nested, auto-parents await ssh.mkdir('/tmp/x', 'exec') // via shell: mkdir -p /tmp/x ``` -------------------------------- ### new NodeSSH() Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Instantiates a new NodeSSH client. The constructor takes no arguments; all configuration is supplied to the connect method. ```APIDOC ## new NodeSSH() ### Description Creates a new NodeSSH instance. The constructor takes no arguments; all configuration is supplied to the connect method. ### Constructor No arguments. ### Example ```js const { NodeSSH } = require('node-ssh') const ssh = new NodeSSH() ``` ``` -------------------------------- ### withShell(callback, options?) Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Opens a shell via requestShell(options), runs the provided callback with the shell channel, and always destroys the channel afterwards, even if the callback throws. ```APIDOC ## withShell(callback: (channel: ClientChannel) => Promise, options?: PseudoTtyOptions | ShellOptions | false): Promise ### Description Opens a shell via requestShell(options), runs callback(shell), and always destroys the shell channel afterwards (in a finally block), even if the callback throws. ### Parameters - **callback** (function) - Required - Called with the shell channel; must be a function (else AssertionError('callback must be a valid function')). - **options** (PseudoTtyOptions | ShellOptions | false) - Optional - Forwarded to requestShell. ### Request Example ```ts await ssh.withShell(async (shell) => { shell.write('top\n') await waitForPrompt(shell) }, { rows: 40 }) ``` ### Response Returns a Promise that resolves when the callback completes and the shell is destroyed. ``` -------------------------------- ### AcceptConnection, RejectConnection, and Prompt Types Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/types.md Utility types for connection handling and user prompts. ```ts export type AcceptConnection = () => T export type RejectConnection = () => void export interface Prompt { prompt: string echo?: boolean } ``` -------------------------------- ### getDirectory(localDirectory, remoteDirectory, options?) Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Downloads a remote directory tree to a local directory. It walks the remote tree using SFTP and downloads files with configurable concurrency. ```APIDOC ## getDirectory(localDirectory: string, remoteDirectory: string, options?: SSHGetPutDirectoryOptions = {}): Promise ### Description Downloads a remote directory tree locally — the reverse of `putDirectory`. Walks the **remote** tree using `sb-scandir`'s `scanDirectory(remoteDirectory, { recursive, validate, concurrency, fileSystem })` with a custom `fileSystem` adapter over SFTP: `basename`/`join` use `path.posix`, `readdir` wraps `sftp.readdir` returning filenames, `stat` wraps `sftp.stat`. Directories are created locally with `make-dir`; files are downloaded via `this.getFile`. Same option semantics, same `boolean` return (`false` if any file failed), same tick/validate defaults. ### Parameters #### localDirectory (string) - Required Local directory path to download to. #### remoteDirectory (string) - Required Remote directory path to download from. #### options (object) - Optional - **concurrency** (number) - Optional - Number of concurrent transfers. Default is `1`. - **sftp** (object) - Optional - SFTP instance to use. - **transferOptions** (object) - Optional - Options to pass to the underlying transfer. - **recursive** (boolean) - Optional - Whether to scan recursively. Default is `true`. - **tick** (function) - Optional - Called after each file attempt. Signature: `tick(localFile, remoteFile, error: Error | null)`. - **validate** (function) - Optional - Decides whether each scanned item is included. Signature: `validate(path: string): boolean`. Default excludes any path whose basename starts with a dot. ### Request Example ```ts const ok = await ssh.getDirectory('./mirror', '/var/www', { concurrency: 4, validate: (p) => path.posix.basename(p) !== 'cache', }) ``` ### Response #### Success Response (200) - **boolean** - Resolves with `true` if every file transfer succeeded, `false` if any failed. ``` -------------------------------- ### NodeSSH.mkdir(path: string, method?: SSHMkdirMethod, givenSftp?: SFTPWrapper | null): Promise Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Creates a directory on the remote server using either SFTP or exec method. Returns a promise that resolves when the directory is created. ```APIDOC ## NodeSSH.mkdir(path: string, method?: SSHMkdirMethod, givenSftp?: SFTPWrapper | null): Promise ### Description Creates a directory on the remote server using either SFTP or exec method. Returns a promise that resolves when the directory is created. ### Method mkdir ### Parameters - **path** (string) - Required - The remote directory path. - **method** (SSHMkdirMethod) - Optional - 'sftp' or 'exec'. - **givenSftp** (SFTPWrapper | null) - Optional - An existing SFTP wrapper. ### Response #### Success Response - **void** - Resolves when the directory is created. ``` -------------------------------- ### Connect and Perform SSH Operations Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Connect to a server using a private key and perform file transfers, directory uploads, and command execution. ```js const fs = require('fs') const path = require('path') const {NodeSSH} = require('node-ssh') const ssh = new NodeSSH() ssh.connect({ host: 'localhost', username: 'steel', privateKeyPath: '/home/steel/.ssh/id_rsa' }) // or with inline privateKey ssh.connect({ host: 'localhost', username: 'steel', privateKey: Buffer.from('...') }) .then(function() { // Local, Remote ssh.putFile('/home/steel/Lab/localPath/fileName', '/home/steel/Lab/remotePath/fileName').then(function() { console.log("The File thing is done") }, function(error) { console.log("Something's wrong") console.log(error) }) // Array string, 'remote' => string)> ssh.putFiles([{ local: '/home/steel/Lab/localPath/fileName', remote: '/home/steel/Lab/remotePath/fileName' }]).then(function() { console.log("The File thing is done") }, function(error) { console.log("Something's wrong") console.log(error) }) // Local, Remote ssh.getFile('/home/steel/Lab/localPath', '/home/steel/Lab/remotePath').then(function(Contents) { console.log("The File's contents were successfully downloaded") }, function(error) { console.log("Something's wrong") console.log(error) }) // Putting entire directories const failed = [] const successful = [] ssh.putDirectory('/home/steel/Lab', '/home/steel/Lab', { recursive: true, concurrency: 10, // ^ WARNING: Not all servers support high concurrency // try a bunch of values and see what works on your server validate: function(itemPath) { const baseName = path.basename(itemPath) return baseName.substr(0, 1) !== '.' && // do not allow dot files baseName !== 'node_modules' // do not allow node_modules }, tick: function(localPath, remotePath, error) { if (error) { failed.push(localPath) } else { successful.push(localPath) } } }).then(function(status) { console.log('the directory transfer was', status ? 'successful' : 'unsuccessful') console.log('failed transfers', failed.join(', ')) console.log('successful transfers', successful.join(', ')) }) // Command ssh.execCommand('hh_client --json', { cwd:'/var/www' }).then(function(result) { console.log('STDOUT: ' + result.stdout) console.log('STDERR: ' + result.stderr) }) // Command output is trimmed by default. Pass noTrim when leading or trailing // whitespace is meaningful, such as reading exact file contents. ssh.execCommand('git show --textconv HEAD:README.md', { noTrim: true }).then(function(result) { console.log('STDOUT: ' + result.stdout) }) // Command with escaped params ssh.exec('hh_client', ['--json'], { cwd: '/var/www', stream: 'stdout', options: { pty: true } }).then(function(result) { console.log('STDOUT: ' + result) }) // With streaming stdout/stderr callbacks ssh.exec('hh_client', ['--json'], { cwd: '/var/www', onStdout(chunk) { console.log('stdoutChunk', chunk.toString('utf8')) }, onStderr(chunk) { console.log('stderrChunk', chunk.toString('utf8')) }, }) }) ``` -------------------------------- ### putDirectory(localDirectory, remoteDirectory, options?) Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Uploads an entire local directory tree to a remote server. It scans the local directory, creates remote directories, and uploads files with configurable concurrency. ```APIDOC ## putDirectory(localDirectory: string, remoteDirectory: string, options?: SSHGetPutDirectoryOptions = {}): Promise ### Description Uploads an entire local directory tree to the remote. Uses `scanDirectory(localDirectory, { recursive, validate })` (from `sb-scandir`) to walk the tree; directory paths are made relative to `localDirectory`, sorted shortest-first, and created remotely via `this.mkdir(..., 'sftp', sftp)`; then every file is uploaded via `this.putFile` under a `PromiseQueue({ concurrency })`. ### Parameters #### localDirectory (string) - Required Local directory path to upload. #### remoteDirectory (string) - Required Remote directory path to upload to. #### options (object) - Optional - **concurrency** (number) - Optional - Number of concurrent transfers. Default is `1`. - **sftp** (object) - Optional - SFTP instance to use. - **transferOptions** (object) - Optional - Options to pass to the underlying transfer. - **recursive** (boolean) - Optional - Whether to scan recursively. Default is `true`. - **tick** (function) - Optional - Called after each file attempt. Signature: `tick(localFile, remoteFile, error: Error | null)`. - **validate** (function) - Optional - Decides whether each scanned item is included. Signature: `validate(path: string): boolean`. Default excludes any path whose basename starts with a dot. ### Request Example ```ts const ok = await ssh.putDirectory('/home/steel/Lab', '/home/steel/Lab', { recursive: true, concurrency: 10, // not all servers support high concurrency - tune per server validate(itemPath) { const base = path.basename(itemPath) return !base.startsWith('.') && base !== 'node_modules' }, tick(local, remote, err) { if (err) failed.push(local) else successful.push(local) }, }) console.log('transfer', ok ? 'ok' : 'had failures') ``` n ### Response #### Success Response (200) - **boolean** - Resolves with `true` if every file transfer succeeded, `false` if any failed. #### Error Response - **AssertionError** - Rejects with `AssertionError` if `localDirectory` does not exist or is not a directory. ``` -------------------------------- ### Download files with getFile Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Downloads a file from the remote server to the local disk using SFTP. ```ts await ssh.getFile('./backup.tar.gz', '/var/backups/last.tar.gz') await ssh.getFile('./db.sql', '/srv/db.sql', null, { concurrency: 8 }) ``` -------------------------------- ### exec(command: string, parameters: string[], options?: SSHExecOptions): Promise | Promise Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Executes a command on the remote server with formatted parameters. Returns a promise that resolves to a string or an SSHExecCommandResponse depending on the stream option. ```APIDOC ## exec(command: string, parameters: string[], options?: SSHExecOptions): Promise | Promise ### Description Formatted command execution: builds `${command} ${shellEscape(parameters)}`, then delegates to `execCommand`. All parameters must be strings (`AssertionError('parameters must be a valid array')`, `'parameters[${i}] must be a valid string'`) and `options.stream` must be one of `'both'`, `'stdout'`, `'stderr'`. ### Parameters - **command** (string) - Required - The command to execute. - **parameters** (string[]) - Required - Array of parameters to pass to the command. - **options** (SSHExecOptions) - Optional - Options object, including `stream`. ### Return Type - `Promise` when `options.stream` is `undefined`, `'stdout'`, or `'stderr'`. - `Promise` when `options.stream` is `'both'`. ### Behavior - If `options.stream` is `undefined` or `'stdout'`, returns `response.stdout`; throws `new Error(response.stderr)` if `response.stderr` is non-empty. - If `options.stream` is `'stderr'`, returns `response.stderr` without throwing. - If `options.stream` is `'both'`, returns the whole response object. ### Example ```ts const hash = await ssh.exec('sha1sum', ['package.json']) // runs: sha1sum package.json await ssh.exec('hh_client', ['--json'], { cwd: '/var/www', stream: 'stdout' }) // error handling: stderr causes rejection with an Error whose message is the stderr text try { await ssh.exec('node', ['-e', 'console.error("boom")']) } catch (err) { console.log(err.message) // "boom" } ``` ``` -------------------------------- ### Download directory with getDirectory Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Downloads a remote directory tree to the local filesystem. Uses a custom file system adapter over SFTP to walk the remote tree. ```ts const ok = await ssh.getDirectory('./mirror', '/var/www', { concurrency: 4, validate: (p) => path.posix.basename(p) !== 'cache', }) ``` -------------------------------- ### withSFTP(callback) Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Requests an SFTP session, runs the provided callback with the SFTP wrapper, and always calls sftp.end() in a finally block. ```APIDOC ## withSFTP(callback: (sftp: SFTPWrapper) => Promise): Promise ### Description Requests an SFTP session, runs callback(sftp), and always calls sftp.end() in a finally block. The wrapper obtained by this method is safe to pass as the sftp option of getFile/putFile/putFiles/putDirectory/getDirectory/mkdir — those methods then do not close it themselves. ### Parameters - **callback** (function) - Required - Called with the SFTPWrapper; must be a function. ### Request Example ```ts await ssh.withSFTP(async (sftp) => { await new Promise((resolve, reject) => sftp.fastPut('a-txt', '/remote/a-txt', (err) => err ? reject(err) : resolve())) }) ``` ### Response Returns a Promise that resolves when the callback completes and the SFTP session is ended. ``` -------------------------------- ### SSHGetPutDirectoryOptions Interface Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/types.md Configuration options for NodeSSH.putDirectory and NodeSSH.getDirectory, extending SSHPutFilesOptions. ```ts export interface SSHGetPutDirectoryOptions extends SSHPutFilesOptions { tick?: (localFile: string, remoteFile: string, error: Error | null) => void validate?: (path: string) => boolean recursive?: boolean } ``` -------------------------------- ### Enable keyboard-interactive authentication Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Use the tryKeyboard option to enable keyboard-interactive authentication. A custom onKeyboardInteractive callback can be provided to handle specific prompts, such as password entry. ```js const password = 'test' ssh.connect({ host: 'localhost', username: 'steel', port: 22, password, tryKeyboard: true, }) // Or if you want to add some custom keyboard-interactive logic: ssh.connect({ host: 'localhost', username: 'steel', port: 22, tryKeyboard: true, onKeyboardInteractive(name, instructions, instructionsLang, prompts, finish) { if (prompts.length > 0 && prompts[0].prompt.toLowerCase().includes('password')) { finish([password]) } } }) ``` -------------------------------- ### SSHGetPutDirectoryOptions Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/types.md Options object for NodeSSH.putDirectory and NodeSSH.getDirectory. Extends SSHPutFilesOptions with tick, validate, and recursive fields. ```APIDOC ## SSHGetPutDirectoryOptions ### Description Options object for `NodeSSH.putDirectory` and `NodeSSH.getDirectory`. Extends `SSHPutFilesOptions`. ### Fields - **tick** (function) - Optional - Called after every file attempt; `error` is non-null when that file's transfer failed. Default: no-op (`DEFAULT_TICK`). - **validate** (function) - Optional - Inclusion predicate for every scanned path. Default: excludes paths whose basename starts with `.` (`DEFAULT_VALIDATE`). - **recursive** (boolean) - Optional - Whether to descend into subdirectories (default `true`). - **sftp** - Inherited from `SSHPutFilesOptions`. - **concurrency** - Inherited from `SSHPutFilesOptions`. - **transferOptions** - Inherited from `SSHPutFilesOptions`. ### TypeScript Definition ```ts export interface SSHGetPutDirectoryOptions extends SSHPutFilesOptions { tick?: (localFile: string, remoteFile: string, error: Error | null) => void validate?: (path: string) => boolean recursive?: boolean } ``` ``` -------------------------------- ### putFiles(files, options?) Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Bulk uploads multiple files to a remote server. It uses a promise queue with configurable concurrency and mutates the error object with a list of successfully transferred files on failure. ```APIDOC ## putFiles(files: { local: string; remote: string }[], options?: SSHPutFilesOptions = {}): Promise ### Description Bulk upload controlled by `sb-promise-queue`'s `PromiseQueue({ concurrency })` (default concurrency `1`). Every item must be an object with non-empty string `local` and `remote` — violations reject with `AssertionError` (`'files must be an array'`, `'files items must be valid objects'`, `'files[${i}].local must be a string'`, `'files[${i}].remote must be a string'`). Internally calls `this.putFile` per item with the shared session and `transferOptions`. Error semantics: if any transfer fails, the rejection error is **mutated in place** with `error.transferred = transferred` — an array of the `{ local, remote }` items that had already succeeded. The mutation is skipped if the error is nullish. ### Parameters #### files (array of objects) - Required - **local** (string) - Required - Local file path. - **remote** (string) - Required - Remote file path. #### options (object) - Optional - **concurrency** (number) - Optional - Number of concurrent transfers. Default is `1`. ### Request Example ```ts const files = [ { local: 'a.js', remote: '/srv/static/a.js' }, { local: 'b.js', remote: '/srv/static/b.js' }, ] try { await ssh.putFiles(files, { concurrency: 5 }) } catch (err) { console.log('succeeded so far:', err.transferred) } ``` n ### Response #### Success Response (200) - **void** - Resolves with `void` on success. #### Error Response - **AssertionError** - Rejects with `AssertionError` if input validation fails. - **Error** - Rejects with an `Error` object that has a `transferred` property (array of successfully transferred items) if any transfer fails. ``` -------------------------------- ### ExecOptions Interface Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/types.md Options for executing commands, accepted via SSHExecCommandOptions. ```ts export interface ExecOptions { env?: NodeJS.ProcessEnv pty?: PseudoTtyOptions | boolean x11?: X11Options | number | boolean allowHalfOpen?: boolean } ``` -------------------------------- ### execCommand(givenCommand, options?) Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Executes a single command over a new SSH channel, collecting stdout/stderr until the channel closes. Supports options like cwd, stdin, onChannel, onStdout, onStderr, encoding, and noTrim. ```APIDOC ## execCommand(givenCommand: string, options?: SSHExecCommandOptions): Promise ### Description Executes a single command over a new SSH channel, collecting stdout/stderr until the channel closes. If options.cwd is set, the command is rewritten to `${shellEscape([options.cwd])} ; ${command}`. The cd failure is not swallowed since v8.0.0 — its stderr flows into the response's stderr. ### Parameters - **givenCommand** (string) - Required - The command to execute. - **options** (SSHExecCommandOptions) - Optional - Configuration options. - **cwd** (string) - Optional - Working directory for the command. - **stdin** (string | stream.Readable) - Optional - Input to send to the command's stdin. - **onChannel** (function) - Optional - Called with the raw ClientChannel as soon as the channel is created. - **onStdout** (function) - Optional - Called with raw Buffer chunks of stdout before concatenation and decoding. - **onStderr** (function) - Optional - Called with raw Buffer chunks of stderr before concatenation and decoding. - **encoding** (string) - Optional - Encoding for decoding output (default utf8). - **noTrim** (boolean) - Optional - If true, output is not trimmed (default false). ### Request Example ```ts const res = await ssh.execCommand('git show --textconv HEAD:README.md', { noTrim: true }) console.log(res.stdout, res.stderr, res.code, res.signal) // stdin + streaming callbacks + custom cwd await ssh.execCommand('node -e "process.stdin.pipe(process.stdout)"', { cwd: '/var/www', stdin: someReadableStream, onStdout(chunk) { process.stdout.write(chunk) }, onStderr(chunk) { process.stderr.write(chunk) }, encoding: 'utf8', onChannel(channel) { channel.setWindow(80, 24) }, }) ``` ### Response Returns a Promise that resolves to an object with properties: stdout (string), stderr (string), code (number | null), signal (string | null). ``` -------------------------------- ### requestShell(options?: PseudoTtyOptions | ShellOptions | false): Promise Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Requests an interactive shell (ssh2 Client.shell()), returning the ClientChannel. Options are passed through to ssh2 when non-null; false, null, or undefined invokes the no-options overload. ```APIDOC ## requestShell(options?: PseudoTtyOptions | ShellOptions | false): Promise ### Description Requests an interactive shell (ssh2 `Client.shell()`), returning the `ClientChannel`. `options` is passed straight through to ssh2 when non-null; `false`, `null`, or `undefined` invokes the no-options overload. A transient `error` listener on the client rejects the promise and is removed once the callback fires. ### Parameters #### Optional Parameters - `options` (PseudoTtyOptions | ShellOptions | false) - Optional - Options for the shell, passed directly to ssh2. If false, null, or undefined, the no-options overload is used. ### Returns - `Promise` - A Duplex stream representing the shell channel. Unlike `withShell`, the channel is **not** closed for you. ### Example ```ts const shell = await ssh.requestShell({ rows: 30, cols: 120 }) shell.on('data', (chunk) => process.stdout.write(chunk.toString())) shell.write('ls -la\n') ``` ### Error Handling Rejects with the ssh2 error if the shell cannot be created. ``` -------------------------------- ### ConnectConfig Interface Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/types.md Configuration options for establishing an SSH connection, imported from ssh2. ```ts export interface ConnectConfig { host?: string port?: number forceIPv4?: boolean forceIPv6?: boolean hostHash?: string hostVerifier?: HostVerifier | SyncHostVerifier | HostFingerprintVerifier | SyncHostFingerprintVerifier username?: string password?: string agent?: BaseAgent | string privateKey?: Buffer | string passphrase?: Buffer | string localHostname?: string localUsername?: string tryKeyboard?: boolean keepaliveInterval?: number keepaliveCountMax?: number readyTimeout?: number strictVendor?: boolean sock?: Readable agentForward?: boolean algorithms?: Algorithms debug?: DebugFunction authHandler?: AuthenticationType[] | AuthHandlerMiddleware | AuthMethod[] localAddress?: string localPort?: number timeout?: number ident?: Buffer | string } ``` -------------------------------- ### Configure tsconfig.json Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Recommended compiler options for projects using node-ssh with TypeScript. ```json { "compilerOptions": { "moduleResolution": "node", "allowSyntheticDefaultImports": true } } ``` -------------------------------- ### SSHPutFilesOptions Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/types.md Options object for NodeSSH.putFiles(files, options). Also the base of SSHGetPutDirectoryOptions. ```APIDOC ## SSHPutFilesOptions ### Description Options object for `NodeSSH.putFiles(files, options)`; also the base of `SSHGetPutDirectoryOptions`. ### Fields - **sftp** (SFTPWrapper | null) - Optional - Reuse an existing SFTP session (e.g. from `withSFTP`); when null/omitted a session is opened and closed by the call. - **concurrency** (number) - Optional - Max parallel transfers (default `1` via `DEFAULT_CONCURRENCY`). - **transferOptions** (TransferOptions) - Optional - Forwarded to `fastGet`/`fastPut` (`concurrency`, `chunkSize`, `fileSize`, `step`, `mode`). ``` -------------------------------- ### withShell: Open a shell with cleanup Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Opens a shell via requestShell(options), runs the callback with the shell channel, and always destroys the channel in a finally block. The callback must be a function, otherwise an AssertionError is thrown. Options are forwarded to requestShell. ```TypeScript await ssh.withShell(async (shell) => { shell.write('top\n') await waitForPrompt(shell) }, { rows: 40 }) ``` -------------------------------- ### NodeSSH.withSFTP(callback: (sftp: SFTPWrapper) => Promise): Promise Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Opens an SFTP session, invokes the provided callback with the SFTP wrapper, and ensures the session is closed after the callback completes. Returns a promise that resolves when the session ends. ```APIDOC ## NodeSSH.withSFTP(callback: (sftp: SFTPWrapper) => Promise): Promise ### Description Opens an SFTP session, invokes the provided callback with the SFTP wrapper, and ensures the session is closed after the callback completes. Returns a promise that resolves when the session ends. ### Method withSFTP ### Parameters - **callback** (function) - Required - Async callback that receives the SFTPWrapper. ### Response #### Success Response - **void** - Resolves when the SFTP session is finished. ``` -------------------------------- ### Upload files with putFile Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Uploads a local file to the remote server, automatically creating parent directories if necessary. ```ts await ssh.putFile('local/bundle.js', '/var/www/static/bundle.js') // reuse a session from withSFTP so it is not closed per-call await ssh.withSFTP(async (sftp) => { await ssh.putFile('a', '/rmt/a', sftp) await ssh.putFile('b', '/rmt/b', sftp) }) ``` -------------------------------- ### SSHPutFilesOptions Interface Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/types.md Options object for NodeSSH.putFiles, serving as the base for SSHGetPutDirectoryOptions. ```ts export interface SSHPutFilesOptions { sftp?: SFTPWrapper | null concurrency?: number transferOptions?: TransferOptions } ``` -------------------------------- ### withSFTP: SFTP session with guaranteed cleanup Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Requests an SFTP session, runs the callback with the SFTPWrapper, and always calls sftp.end() in a finally block. The wrapper is safe to pass as the sftp option of getFile/putFile/putFiles/putDirectory/getDirectory/mkdir, which then do not close it themselves. ```TypeScript await ssh.withSFTP(async (sftp) => { await new Promise((resolve, reject) => sftp.fastPut('a-txt', '/remote/a-txt', (err) => err ? reject(err) : resolve())) }) ``` -------------------------------- ### requestSFTP() Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Requests an SFTP subsystem (ssh2 Client.sftp()), resolving with the SFTPWrapper. Use withSFTP when you want guaranteed cleanup; raw requestSFTP leaves ownership to the caller. ```APIDOC ## requestSFTP(): Promise ### Description Requests an SFTP subsystem (ssh2 Client.sftp()), resolving with the SFTPWrapper. Throws synchronously with Error('Not connected to server') when disconnected, and rejects if the ssh2 callback reports an error. ### Parameters None. ### Request Example ```ts const sftp = await ssh.requestSFTP() try { await new Promise((resolve, reject) => sftp.readdir('/var/www', (err, items) => err ? reject(err) : resolve(items))) } finally { sftp.end() } ``` ### Response Returns a Promise that resolves to an SFTPWrapper (an ssh2 SFTPWrapper with methods like fastGet, fastPut, readdir, mkdir, stat, end(), etc.). ``` -------------------------------- ### forwardIn(remoteAddr, remotePort, onConnection?) Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Registers a TCP/IP forward on the server. It resolves with details including the bound port and a dispose function to remove the listener. ```APIDOC ## forwardIn(remoteAddr: string, remotePort: number, onConnection?: SSHForwardInListener): Promise ### Description Registers a TCP/IP forward on the server (ssh2 `forwardIn`). The listener runs only for connections whose `details.destIP === remoteAddr` **and** `details.destPort === port`. Resolves with `{ port, dispose }` where `port` is the bound port (the server may assign it when you ask for `0`), and `dispose(): Promise` removes the listener, then calls `unforwardIn`. ### Parameters #### remoteAddr (string) - Required Remote address to forward to. #### remotePort (number) - Required Remote port to forward to. #### onConnection (function) - Optional Listener for incoming connections. Signature: `(etails, accept, reject) => void`. ### Request Example ```ts const { port, dispose } = await ssh.forwardIn('127.0.0.1', 8080, (details, accept, reject) => { console.log(`conn from ${details.srcIP}:${details.srcPort}`) accept() n}) // later await dispose() ``` ### Response #### Success Response (200) - **port** (number) - The bound port. - **dispose** (function) - A function that removes the listener and calls `unforwardIn`. Returns a `Promise`. #### Error Response - **Error** - Rejects with an error if the forward registration fails. In `dispose`, if `unforwardIn` reports an error, the promise rejects with the **outer** forward-registration `error` variable (not the unforward error). ``` -------------------------------- ### NodeSSH.withShell(callback: (channel: ClientChannel) => Promise, options?: PseudoTtyOptions | ShellOptions | false): Promise Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Opens an interactive shell, invokes the provided callback with the channel, and ensures the shell is closed after the callback completes. Returns a promise that resolves when the shell session ends. ```APIDOC ## NodeSSH.withShell(callback: (channel: ClientChannel) => Promise, options?: PseudoTtyOptions | ShellOptions | false): Promise ### Description Opens an interactive shell, invokes the provided callback with the channel, and ensures the shell is closed after the callback completes. Returns a promise that resolves when the shell session ends. ### Method withShell ### Parameters - **callback** (function) - Required - Async callback that receives the ClientChannel. - **options** (PseudoTtyOptions | ShellOptions | false) - Optional - Shell options. ### Response #### Success Response - **void** - Resolves when the shell session is finished. ``` -------------------------------- ### Module Dependency Graph Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/index.md Visual representation of the node-ssh module dependencies and exports from src/index.ts. ```text src/index.ts (exports everything) ├── ssh2 (npm) — Client, ClientChannel, Channel, SFTPWrapper, ConnectConfig, │ ExecOptions, Prompt, PseudoTtyOptions, RejectConnection, │ AcceptConnection, ShellOptions, Stats, TcpConnectionDetails, │ TransferOptions, UNIXConnectionDetails ├── assert (node) — invariant, AssertionError (argument validation) ├── fs (node) — privateKeyPath reading, local stat/access checks ├── path (node) — posix path handling, unixifyPath() ├── stream (node) — stream.Readable type for SSHExecCommandOptions.stdin ├── is-stream — isStream.readable() checks on options.stdin ├── make-dir — local directory creation in getDirectory() ├── sb-promise-queue — PromiseQueue (concurrency limiting in putFiles/putDirectory/getDirectory) ├── sb-scandir — scanDirectory() (walk local + remote trees) └── shell-escape — shellEscape() (parameter escaping for exec()) ``` -------------------------------- ### NodeSSH.execCommand(givenCommand: string, options?: SSHExecCommandOptions): Promise Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Executes a single command on the remote server. Returns a promise that resolves with the command's stdout, stderr, exit code, and signal. ```APIDOC ## NodeSSH.execCommand(givenCommand: string, options?: SSHExecCommandOptions): Promise ### Description Executes a single command on the remote server. Returns a promise that resolves with the command's stdout, stderr, exit code, and signal. ### Method execCommand ### Parameters - **givenCommand** (string) - Required - The command to execute. - **options** (SSHExecCommandOptions) - Optional - Options such as cwd, stdin, encoding, and event handlers. ### Response #### Success Response - **SSHExecCommandResponse** - Object containing stdout, stderr, code, and signal. ``` -------------------------------- ### Upload directory with putDirectory Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Uploads a local directory tree to a remote server. Supports custom validation logic and a tick callback to track progress. ```ts const ok = await ssh.putDirectory('/home/steel/Lab', '/home/steel/Lab', { recursive: true, concurrency: 10, // not all servers support high concurrency - tune per server validate(itemPath) { const base = path.basename(itemPath) return !base.startsWith('.') && base !== 'node_modules' }, tick(local, remote, err) { if (err) failed.push(local) else successful.push(local) }, }) console.log('transfer', ok ? 'ok' : 'had failures') ``` -------------------------------- ### NodeSSH.exec(command: string, parameters: string[], options?: SSHExecOptions): Promise Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Executes a command with parameters on the remote server. Returns a promise that resolves to the output string or an object with stdout and stderr depending on the stream option. ```APIDOC ## NodeSSH.exec(command: string, parameters: string[], options?: SSHExecOptions): Promise ### Description Executes a command with parameters on the remote server. Returns a promise that resolves to the output string or an object with stdout and stderr depending on the stream option. ### Method exec ### Parameters - **command** (string) - Required - The command to execute. - **parameters** (string[]) - Required - Array of parameters to pass to the command. - **options** (SSHExecOptions) - Optional - Options including stream ('stdout' | 'stderr' | 'both'), cwd, stdin, etc. ### Response #### Success Response - **string** - The output when stream is 'stdout' or 'stderr'. - **SSHExecCommandResponse** - Object with stdout and stderr when stream is 'both'. ``` -------------------------------- ### SSHMkdirMethod Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/types.md Type alias for the method argument of NodeSSH.mkdir(path, method). 'sftp' uses the SFTP subsystem (default); 'exec' runs mkdir -p through a shell. ```APIDOC ## SSHMkdirMethod ### Description Type alias for the `method` argument of `NodeSSH.mkdir(path, method)`. `'sftp'` uses the SFTP subsystem (default); `'exec'` runs `mkdir -p` through a shell. ### TypeScript Definition ```ts export type SSHMkdirMethod = 'sftp' | 'exec' ``` ``` -------------------------------- ### SSHExecCommandOptions Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/types.md Options object for NodeSSH.execCommand(command, options). ```APIDOC ## SSHExecCommandOptions ### Description Options object for `NodeSSH.execCommand(command, options)`. ### Fields - **cwd** (string) - optional - Working directory; the command is prefixed with `cd ; `. - **stdin** (string | stream.Readable) - optional - Input written to the child process' stdin. A Readable is piped with `end: true`; a string is written and the channel ended. - **execOptions** (ExecOptions) - optional - Passed directly to ssh2 `Client.exec()` as its options argument (e.g. `{ pty: true }`, `{ env: {...} }`, `{ allowHalfOpen }`). - **encoding** (BufferEncoding) - optional - Charset used to decode stdout/stderr chunks into strings (default `'utf8'`). - **noTrim** (boolean) - optional - When `true`, stdout/stderr are not `.trim()`ed (added v13.2.0). - **onChannel** ((clientChannel: ClientChannel) => void) - optional - Called with the raw `ClientChannel` immediately after it is created. - **onStdout** ((chunk: Buffer) => void) - optional - Called with each raw stdout chunk (before encoding/trim). - **onStderr** ((chunk: Buffer) => void) - optional - Called with each raw stderr chunk. ### Example ```ts interface SSHExecCommandOptions { cwd?: string stdin?: string | stream.Readable execOptions?: ExecOptions encoding?: BufferEncoding noTrim?: boolean onChannel?: (clientChannel: ClientChannel) => void onStdout?: (chunk: Buffer) => void onStderr?: (chunk: Buffer) => void } ``` ``` -------------------------------- ### Connect with custom keyboard-interactive logic Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Provides a custom handler for keyboard-interactive authentication, useful for non-password prompts. ```typescript // Custom keyboard-interactive logic (e.g. non-password prompts) await ssh.connect({ host: 'localhost', username: 'steel', port: 22, tryKeyboard: true, onKeyboardInteractive(name, instructions, instructionsLang, prompts, finish) { if (prompts.length > 0 && prompts[0].prompt.toLowerCase().includes('password')) { finish([password]) } }, }) ``` -------------------------------- ### Bulk upload files with putFiles Source: https://github.com/steelbrain/node-ssh/blob/main/_autodocs/api.md Uploads multiple files concurrently using a promise queue. If a transfer fails, the error object is mutated to include a list of successfully transferred files. ```ts const files = [ { local: 'a.js', remote: '/srv/static/a.js' }, { local: 'b.js', remote: '/srv/static/b.js' }, ] try { await ssh.putFiles(files, { concurrency: 5 }) } catch (err) { console.log('succeeded so far:', err.transferred) } ```