• Stars
    star
    866
  • Rank 52,675 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

SSH2 with Promises

Node-SSH - SSH2 with Promises

Node-SSH is an extremely lightweight Promise wrapper for ssh2.

Installation

$ npm install node-ssh # If you're using npm
$ yarn add node-ssh # If you're using Yarn

Example

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<Shape('local' => 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 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'))
    },
  })
})

API

// API reference in Typescript typing format:
import stream from 'stream'
import { Client, ConnectConfig, ClientChannel, SFTPWrapper, ExecOptions, PseudoTtyOptions | ShellOptions } from 'ssh2';
import { Prompt, TransferOptions } from 'ssh2-streams';
// ^ You do NOT need to import these package, these are here for reference of where the
// types are coming from.

declare type Config = ConnectConfig & {
    host?: string;
    port?: number;
    username?: string;
    password?: string;
    privateKeyPath?: string;
    privateKey?: string;
    passphrase?: string;
    tryKeyboard?: boolean;
    onKeyboardInteractive?: (
      name: string,
      instructions: string,
      lang: string,
      prompts: Prompt[],
      finish: (responses: string[]) => void
    ) => void;
};

interface SSHExecCommandOptions {
    cwd?: string;
    stdin?: string | stream.Readable;
    execOptions?: ExecOptions;
    encoding?: BufferEncoding;
    onChannel?: (clientChannel: ClientChannel) => void;
    onStdout?: (chunk: Buffer) => void;
    onStderr?: (chunk: Buffer) => void;
}

interface SSHExecCommandResponse {
    stdout: string;
    stderr: string;
    code: number | null;
    signal: string | null;
}

interface SSHExecOptions extends SSHExecCommandOptions {
    stream?: 'stdout' | 'stderr' | 'both';
}

interface SSHPutFilesOptions {
    sftp?: SFTPWrapper | null;
    concurrency?: number;
    transferOptions?: TransferOptions;
}

interface SSHGetPutDirectoryOptions extends SSHPutFilesOptions {
    tick?: (localFile: string, remoteFile: string, error: Error | null) => void;
    validate?: (path: string) => boolean;
    recursive?: boolean;
}

type SSHForwardInListener = (
  details: TcpConnectionDetails,
  accept: AcceptConnection<ClientChannel>,
  reject: RejectConnection,
) => void
interface SSHForwardInDetails {
  dispose(): Promise<void>
  port: number
}

type SSHForwardInStreamLocalListener = (
  info: UNIXConnectionDetails,
  accept: AcceptConnection,
  reject: RejectConnection,
) => void
interface SSHForwardInStreamLocalDetails {
  dispose(): Promise<void>
}

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?: 'sftp' | 'exec',
      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
    ): Promise<void>;

    putFiles(files: Array<{
        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;
}

module.exports = NodeSSH;

Typescript support

node-ssh requires extra dependencies while working under Typescript. Please install them as shown below

yarn add --dev @types/ssh2
# OR
npm install --save-dev @types/ssh2

If you're still running into issues, try adding these to your tsconfig.json

{
  "compilerOptions": {
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true
  }
}

Keyboard-interactive user authentication

In some cases you have to enable keyboard-interactive user authentication. Otherwise you will get an All configured authentication methods failed error.

Example:

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])
    }
  }
})

For further information see: mscdex/ssh2#604

License

This project is licensed under the terms of MIT license. See the LICENSE file for more info.

More Repositories

1

linter

A Base Linter with Cow Powers http://steelbrain.me/linter/
JavaScript
1,096
star
2

motion

javascript cli: fast, configurable, easy, with hmr
618
star
3

pundle

πŸ‘Ύ peaceful bundles - js bundler, built from the ground up for speed and extensibility
JavaScript
358
star
4

flow-ide

A full featured FlowType package for Atom Editor
JavaScript
202
star
5

denode

Debug node apps like a pro
JavaScript
142
star
6

ffmpeg-over-ip

Connect to remote ffmpeg servers
JavaScript
110
star
7

php-serialize

PHP Serialize/Unserialize in Javascript
TypeScript
109
star
8

Worker-Exchange

Human-Friendly Web Worker wrapper.
JavaScript
104
star
9

linter-ui-default

Default UI for the Atom Linter package
TypeScript
84
star
10

package-deps

Automatically install dependencies for your atom packages
TypeScript
59
star
11

busy-signal

A base Atom package that provides an easy to use API to show your package is performing a task
JavaScript
58
star
12

Smart-Polyfill

A smart polyfill server for browsers written in Node
JavaScript
56
star
13

intentions

Base package for showing intentions in Atom
JavaScript
53
star
14

atom-linter

Helper module for linter providers
JavaScript
30
star
15

Brauser

A Web-Native Cross Platform Web Browser.
JavaScript
21
star
16

razer-blade-17-pro-2020-hackintosh

Hackintosh configuration for macOS Catalina to run on a Razer Blade 17 Pro 2020
ASL
20
star
17

Atom-Hack

HackLang Package for Atom Editor
JavaScript
19
star
18

babel-plugin-remove-unused-vars

Babel plugin to remove unused variables and imports (Babel autofix for ESLint's no-unused-vars)
TypeScript
18
star
19

mariasql-promise

A lightweight Promise wrapper for MariaSQL (MySQL Compatible)
JavaScript
13
star
20

autocomplete-swift

Swift autocomplete provider
JavaScript
11
star
21

event-kit

Lightweight library to create disposable components
JavaScript
10
star
22

HHVM-Async-Server

Async Socket Server Experiment in HHVM's HackLang
Hack
9
star
23

exec

Node's Process spawning APIs beautified
JavaScript
9
star
24

consistent-env

A reliable way to get env in Node
JavaScript
9
star
25

project-config

Project-specific config helper for Atom
JavaScript
9
star
26

ucompiler

Depreciated: UCompiler is a Compiler / Minifier / Concatenator / Transpiler for all of your web assets
JavaScript
7
star
27

autocomplete-hack

Hack Lang AutoComplete for Atom Editor
JavaScript
6
star
28

jsx-string

JSX in strings out
JavaScript
6
star
29

Async-Redis

Async Redis Pub/Sub in HackLang
Hack
6
star
30

eslint-config

My eslintrc
JavaScript
6
star
31

declarations

A base package that lets other packages allow user to jump to declaration
JavaScript
5
star
32

bibi

A repository management tool
JavaScript
5
star
33

consistent-path

A module to get correct $PATH on OSX that does not modify globals
JavaScript
5
star
34

RedisNG-Node

A tiny yet Powerful Promise based Redis Client for Node.js
JavaScript
5
star
35

babel-cli

A smarter babel-cli
TypeScript
5
star
36

apollo-link-firestore

Query Google Firebase Firestore with GraphQL in Apollo
TypeScript
5
star
37

downloader

A node.js multi-connection downloader
JavaScript
5
star
38

apollo-link-firebase-ng

Query/Subscribe to Firebase Realtime DB with GraphQL/Apollo.
TypeScript
4
star
39

react-table

React Table Component done right
JavaScript
4
star
40

fs

Promisified fs for Node.js
JavaScript
4
star
41

promise-queue

Sequential promise queue with a nice API
TypeScript
4
star
42

command

CLI command and options parser
JavaScript
4
star
43

expected-write

A promise based expect-and-write for child_processes and streams
CoffeeScript
4
star
44

process-communication

Makes promise-based inter process communication easy
JavaScript
4
star
45

declarations-js

Atom package for Javascript support for Jump to Declaration
JavaScript
4
star
46

vanilla-jsx

Deprecated: A lightweight library that converts JSX into HTMLElements
JavaScript
4
star
47

redis-proto

Redis Protocol Encode/Decode in NodeJS
JavaScript
4
star
48

promise.defer

Lightweight Promise.defer implementation
TypeScript
3
star
49

promisify

Node module for simple promisification
JavaScript
3
star
50

cool-trim

Trim weird strings to sanity
JavaScript
3
star
51

npm-path

Get PATH of your node runtime and modules
JavaScript
3
star
52

process-lockfile

Lockfiles for Node.js with extended capabilities
JavaScript
3
star
53

pexchange

A promise based inter-process data exchange
JavaScript
3
star
54

Happy-DB

A Redis protocol compatible NoSQL Database written entirely in NodeJS
JavaScript
3
star
55

steelbrain.github.io

CSS
3
star
56

socket.io-php-emitter

Dead Simple Socket.io Emitter for PHP (HHVM Compatible)
PHP
3
star
57

communication

A communication library for communication libraries
JavaScript
3
star
58

memoize

Memoization in JS made easy
JavaScript
3
star
59

atom-autocomplete

Collection of node helpers for Atom's autocomplete providers
JavaScript
3
star
60

resolve

Deprecated use substack/resolve instead; require.resolve algorithm implemented with awesome features
JavaScript
3
star
61

publish

Things I use to publish my packages
JavaScript
2
star
62

scandir

File scanning module for Node.js
TypeScript
2
star
63

lint-unpushed

Lint Unpushed will make sure your code passes relevant tests before you git push
JavaScript
2
star
64

package-info

Get information about NPM packages
JavaScript
2
star
65

debounce

Debouncing functions made easy
JavaScript
2
star
66

tagged-template-literals

A base library to make your packages simpler.
JavaScript
2
star
67

universal-compiler

Depreciated: Universal-Compiler is a Compiler / Minifier / Concatenator / Transpiler for all of your web assets.
JavaScript
2
star
68

class-validators

ES Decorators for function param validation
JavaScript
1
star
69

redux-memory

Redux Persistence made simple
JavaScript
1
star
70

js-toolkit

A toolkit for being more productive with Javascript.
JavaScript
1
star
71

babel-preset-es2015-sane

The mirror of babel-preset-es2015 without the regenerator requirement
JavaScript
1
star
72

alarm-server-mqtt

EZVIZ Alarm server to MQTT server events
TypeScript
1
star
73

babel-plugin-defer-logic

Defer logic to be executed in JS functions
TypeScript
1
star
74

spawn

Node's Process spawning APIs beautified, lightweight with no dependencies
TypeScript
1
star
75

websocket-promise

Deprecated: A Promise-based websocket server
JavaScript
1
star
76

copy

Smooth recursive copies in Node.js
JavaScript
1
star
77

custom-element-base

A base component for declaring custom elements
CoffeeScript
1
star
78

intentions-numbers

A package that allows you to hold numbers in text editor and increase/decrease them on mouse move
JavaScript
1
star
79

link-tilde

Node.js module to get nicer import paths
JavaScript
1
star
80

callsite

Optimized stack traces for Javascript - Archived because feature-complete / stable
JavaScript
1
star
81

node-youtube-dl

A Youtube-DL downloader interface for node
JavaScript
1
star
82

package-upgrader

Auto-Updater for atom packages
JavaScript
1
star
83

babel-preset

My personal babel preset
JavaScript
1
star
84

canvas-game

A simple html5 2d monster capturing game
JavaScript
1
star
85

atom-package-ideas

Repository with Ideas for Atom Packages. Have a suggestion? Open an issue and tell me about it
1
star
86

disposify

Convert any type of object into a disposable
JavaScript
1
star
87

x-notification

Codedrops notifications as HTML5 Custom Element
CSS
1
star