Skip to content

doc supplementary for connection hoping and agent forwarding #764

@YxxY

Description

@YxxY

After some hard work, Finally, I achieve connection hoping in a general way with forwardOut as follows

var Client = require('ssh2').Client;

var conn1 = new Client();
var conn2 = new Client();

conn1.on('ready', function () {
  console.log('FIRST :: connection ready');
  conn1.forwardOut('127.0.0.1', 8000, '192.168.1.2', 22, function (err, stream) {
    if (err) {
      console.log('FIRST :: exec error: ' + err);
      return conn1.end();
    }
    conn2.connect({
      sock: stream,
      host: '192.168.1.2',
      port: 22,
      username: 'username2',
      password: 'password2',
    });
  });
}).connect({
  host: '192.168.1.1',
  port: 22,
  username: 'username1',
  password: 'password1',
});

conn2.on('ready', function () {
  console.log('SECOND :: connection ready');
  conn2.exec('uptime', function (err, stream) {
    if (err) {
      console.log('SECOND :: exec error: ' + err);
      return conn1.end();
    }
    stream.on('end', function () {
      conn1.end(); // close parent (and this) connection
    }).on('data', function (data) {
      console.log(data.toString());
    });
  });
});

as for ssh-agent and agent forward scenario

var Client = require('ssh2').Client;

var conn1 = new Client();
var conn2 = new Client();

conn1.on('ready', function () {
  console.log('FIRST :: connection ready');
  conn1.forwardOut('127.0.0.1', 8000, '192.168.1.2', 22, function (err, stream) {
    if (err) {
      console.log('FIRST :: exec error: ' + err);
      return conn1.end();
    }
    conn2.connect({
      sock: stream,
      host: '192.168.1.2',
      port: 22,
      username: 'sora',
      agent: '/path/to/SSH_AUTH_SOCK',
      agentForward: true
    });
  });
}).connect({
  host: '192.168.1.1',
  port: 22,
  username: 'sora',
  agent: '/path/to/SSH_AUTH_SOCK',
});

conn2.on('ready', function () {
  console.log('SECOND :: connection ready');
  conn2.exec('uptime', function (err, stream) {
    if (err) {
      console.log('SECOND :: exec error: ' + err);
      return conn1.end();
    }
    stream.on('end', function () {
      conn1.end(); // close parent (and this) connection
    }).on('data', function (data) {
      console.log(data.toString());
    });
  });
});

It serves me fine! hope for helping those who had been bothered by the nc command in the example readme

Furthermore, In this example, I use 8000 as the local port, I wonder whether I have to be responsible for this number, for I think it should be dynamic or can be omitted. @mscdex

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions