### Installing Node-SSH via npm or Yarn (sh) Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Instructions on how to install the node-ssh library using either the npm or Yarn package managers. This is the first step required to use the library in a Node.js project. ```sh $ npm install node-ssh # If you're using npm $ yarn add node-ssh # If you're using Yarn ``` -------------------------------- ### Installing Node-SSH Typescript Type Definitions Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Commands to install the necessary `@types/ssh2` package as a development dependency using either Yarn or npm, required for Typescript support with `node-ssh`. ```shell yarn add --dev @types/ssh2 # OR npm install --save-dev @types/ssh2 ``` -------------------------------- ### Downloading a File via SSH (js) Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Example of using the `getFile` method to download a file from a remote path on the SSH server to a specified local path. The Promise resolves with the file contents upon successful download. ```js 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) }) ``` -------------------------------- ### Executing a Command via SSH (js) Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Example using `execCommand` to run a command on the remote server. This method returns a Promise that resolves with an object containing the command's standard output and standard error streams. ```js ssh.execCommand('hh_client --json', { cwd:'/var/www' }).then(function(result) { console.log('STDOUT: ' + result.stdout) console.log('STDERR: ' + result.stderr) }) ``` -------------------------------- ### Uploading a Single File via SSH (js) Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Example of using the `putFile` method to transfer a single local file to a specified remote path on the connected SSH server. It includes basic Promise handling for success and error cases. ```js 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) }) ``` -------------------------------- ### Connecting to SSH Server with Private Key Path (js) Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Demonstrates how to establish an SSH connection using a configuration object that specifies the host, username, and the file path to the private key. This is a common method for authenticating with an SSH server. ```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' }) ``` -------------------------------- ### Configuring Keyboard-Interactive Authentication in node-ssh Source: https://github.com/steelbrain/node-ssh/blob/main/README.md This snippet demonstrates two ways to configure node-ssh for keyboard-interactive authentication: using the simple `tryKeyboard: true` option to let the library handle it, or providing a custom `onKeyboardInteractive` function to implement specific logic for responding to prompts, such as providing a password. ```javascript 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]) } } }) ``` -------------------------------- ### Uploading a Directory via SSH (js) Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Shows how to transfer an entire local directory to a remote location using `putDirectory`. It includes options for recursive transfer, concurrency, validation callbacks to exclude files, and a tick callback to track progress and failures. ```js 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(', ')) }) ``` -------------------------------- ### Recommended tsconfig.json Settings for Node-SSH Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Suggests adding `moduleResolution: "node"` and `allowSyntheticDefaultImports: true` to the `compilerOptions` in your `tsconfig.json` file to resolve potential Typescript compilation issues when using `node-ssh`. ```json { "compilerOptions": { "moduleResolution": "node", "allowSyntheticDefaultImports": true } } ``` -------------------------------- ### Executing Command with Streaming Output via SSH (js) Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Shows how to handle command output as it streams using the `onStdout` and `onStderr` options with the `exec` method. This is useful for long-running commands or processing output incrementally. ```js ssh.exec('hh_client', ['--json'], { cwd: '/var/www', onStdout(chunk) { console.log('stdoutChunk', chunk.toString('utf8')) }, onStderr(chunk) { console.log('stderrChunk', chunk.toString('utf8')) } }) ``` -------------------------------- ### Connecting to SSH Server with Inline Private Key (js) Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Shows an alternative method for establishing an SSH connection by providing the private key content directly as a Buffer object in the configuration. This can be useful when the key is not stored in a file. ```js ssh.connect({ host: 'localhost', username: 'steel', privateKey: Buffer.from('...') }) ``` -------------------------------- ### Uploading Multiple Files via SSH (js) Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Demonstrates transferring multiple files simultaneously using the `putFiles` method, which accepts an array of objects specifying local and remote paths for each file. It also includes Promise handling. ```js 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) }) ``` -------------------------------- ### Executing Command with Escaped Parameters via SSH (js) Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Demonstrates using the `exec` method, which allows passing command arguments as an array for proper escaping. It also shows options like specifying the working directory and requesting a PTY. ```js ssh.exec('hh_client', ['--json'], { cwd: '/var/www', stream: 'stdout', options: { pty: true } }).then(function(result) { console.log('STDOUT: ' + result) }) ``` -------------------------------- ### Node-SSH Typescript API Reference Source: https://github.com/steelbrain/node-ssh/blob/main/README.md Provides the Typescript type definitions for the NodeSSH class, configuration options, and various interfaces used throughout the library's API, including connection details, execution options, and file transfer parameters. ```typescript // API reference in Typescript typing format: import SSH2, { AcceptConnection, Channel, ClientChannel, ConnectConfig, ExecOptions, Prompt, PseudoTtyOptions, RejectConnection, SFTPWrapper, ShellOptions, TcpConnectionDetails, TransferOptions, UNIXConnectionDetails, } from 'ssh2' import stream from 'stream' // ^ You do NOT need to import these package, these are here for reference of where the // types are coming from. export type Config = ConnectConfig & { password?: string privateKey?: string privateKeyPath?: string tryKeyboard?: boolean onKeyboardInteractive?: ( name: string, instructions: string, lang: string, prompts: Prompt[], finish: (responses: string[]) => void, ) => void } export 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 } export interface SSHExecCommandResponse { stdout: string stderr: string code: number | null signal: string | null } export interface SSHExecOptions extends SSHExecCommandOptions { stream?: 'stdout' | 'stderr' | 'both' } export interface SSHPutFilesOptions { sftp?: SFTPWrapper | null concurrency?: number transferOptions?: TransferOptions } export interface SSHGetPutDirectoryOptions extends SSHPutFilesOptions { tick?: (localFile: string, remoteFile: string, error: Error | null) => void validate?: (path: string) => boolean recursive?: boolean } export type SSHMkdirMethod = 'sftp' | 'exec' export type SSHForwardInListener = ( details: TcpConnectionDetails, accept: AcceptConnection, reject: RejectConnection, ) => void export interface SSHForwardInDetails { dispose(): Promise port: number } export type SSHForwardInStreamLocalListener = ( info: UNIXConnectionDetails, accept: AcceptConnection, reject: RejectConnection, ) => void export interface SSHForwardInStreamLocalDetails { dispose(): Promise } export class SSHError extends Error { code: string | null constructor(message: string, code?: string | null) } export class NodeSSH { connection: SSH2.Client | null connect(config: Config): Promise isConnected(): boolean requestShell(options?: PseudoTtyOptions | ShellOptions | false): Promise withShell( callback: (channel: ClientChannel) => Promise, options?: PseudoTtyOptions | ShellOptions | false, ): Promise requestSFTP(): Promise withSFTP(callback: (sftp: SFTPWrapper) => Promise): Promise execCommand(givenCommand: string, options?: SSHExecCommandOptions): Promise exec( command: string, parameters: string[], options?: SSHExecOptions & { stream?: 'stdout' | 'stderr' }, ): Promise exec( command: string, parameters: string[], options?: SSHExecOptions & { stream: 'both' }, ): Promise mkdir(path: string, method?: SSHMkdirMethod, givenSftp?: SFTPWrapper | null): Promise getFile( localFile: string, remoteFile: string, givenSftp?: SFTPWrapper | null, transferOptions?: TransferOptions | null, ): Promise putFile( localFile: string, remoteFile: string, givenSftp?: SFTPWrapper | null, transferOptions?: TransferOptions | null, ): Promise putFiles( files: { local: string remote: string }[], { concurrency, sftp: givenSftp, transferOptions }?: SSHPutFilesOptions, ): Promise putDirectory( localDirectory: string, remoteDirectory: string, { concurrency, sftp: givenSftp, transferOptions, recursive, tick, validate }?: SSHGetPutDirectoryOptions, ): Promise getDirectory( localDirectory: string, remoteDirectory: string, { concurrency, sftp: givenSftp, transferOptions, recursive, tick, validate }?: SSHGetPutDirectoryOptions, ): Promise forwardIn(remoteAddr: string, remotePort: number, onConnection?: SSHForwardInListener): Promise forwardOut(srcIP: string, srcPort: number, dstIP: string, dstPort: number): Promise forwardInStreamLocal( socketPath: string, onConnection?: SSHForwardInStreamLocalListener, ): Promise forwardOutStreamLocal(socketPath: string): Promise dispose(): void } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.