SSH2 Client and Server for Node.js

1.17.0 · active · verified Sun Apr 19

ssh2 is a pure JavaScript implementation of an SSH2 client and server for Node.js, enabling secure remote command execution, file transfers (SFTP), and interactive shell sessions. The current stable version is 1.17.0, with development actively maintained against recent OpenSSH versions (e.g., OpenSSH 8.7). This library is distinguished by its comprehensive support for both client and server roles, offering an extensive API for various channel types (exec, shell, direct-tcpip, X11, subsystems) and pluggable authentication methods, including password and public key. It provides fine-grained control over SSH connections, making it suitable for building custom SSH tooling, automating deployments, or implementing secure backend services. While it does not adhere to a strict release cadence, updates are released as features are added or bugs are fixed, ensuring ongoing compatibility and security.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to establish an SSH client connection to a server and execute a remote command ('uptime'), logging its standard output and error.

const { readFileSync } = require('fs');
const { Client } = require('ssh2');

const conn = new Client();
conn.on('ready', () => {
  console.log('Client :: ready');
  conn.exec('uptime', (err, stream) => {
    if (err) throw err;
    stream.on('close', (code, signal) => {
      console.log(`Stream :: close :: code: ${code}, signal: ${signal}`);
      conn.end();
    }).on('data', (data) => {
      console.log('STDOUT: ' + data);
    }).stderr.on('data', (data) => {
      console.error('STDERR: ' + data);
    });
  });
}).on('error', (err) => {
  console.error('Client Error:', err.message);
}).connect({
  host: process.env.SSH_HOST ?? '127.0.0.1',
  port: parseInt(process.env.SSH_PORT ?? '22', 10),
  username: process.env.SSH_USERNAME ?? 'user',
  privateKey: readFileSync(process.env.SSH_PRIVATE_KEY_PATH ?? './id_rsa')
});

view raw JSON →