Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disconnect ssh connection by using node-ssh in node js

Tags:

node.js

Can anyone help me, how t disconnect ssh connection using node-ssh module in node js. Also how to handle error.

my code is

 driver = require('node-ssh');

    ssh = new driver({
              host: '192.168.*.*',
              username: 'user',
              password: 'password',
              privateKey : require('fs').readFileSync('/tmp/my_key')
            });

    ssh.connect().then(function() {
           /*
       some code
        */

            },function(error) {
                console.log(error);

    });

Pls help.

like image 981
selvan Avatar asked May 22 '15 09:05

selvan


3 Answers

Use the dispose method. Example:

const node_ssh = require('node-ssh');
const ssh = new node_ssh();

ssh.connect({
  host: 'XXX',
  username: 'YYY',
  privateKey: 'ZZZ'
}).then(resp => {
  console.log(resp);
  ssh.dispose();
});
like image 140
bersling Avatar answered Nov 15 '22 06:11

bersling


The 'node-ssh' wrapper doesn't seem to provide an 'end' function, or a way to access the underlying ssh2 connection object. That leaves you with a couple options:

Fork the source, write an 'end' method, and issue a pull request to the node-ssh wrapper so that future users can use the wrapper and end the connections. Alternatively, you can create an issue and wait for someone else to create the functionality if/when they deem it necessary.

Use the underlying ssh2 library instead. It exposes a lot more functionality to you, including an 'end' method, to close the connection, but uses callbacks instead of promises, which would require you to refactor your code.

Additionally, you could add the following to your code, though this is very heavily not recommended, as it's messing with a prototype you don't own and could ruin compatibility with future versions of the node-ssh module:

driver.prototype.end = function() {
  this.Connection.end()
  this.Connected = false
}

you can then call ssh.end() to close the connection.

like image 23
Cody Haines Avatar answered Nov 15 '22 04:11

Cody Haines


I've asked directly the creator of the library, here i report the answer:

"Note: If anything of the ssh2 object is not implemented and I am taking more time than I should, You can always use MySSH.Connection.close()"

Issue#9

Then he has done a commit and now you have your method!

ssh.end();
like image 45
SharpEdge Avatar answered Nov 15 '22 05:11

SharpEdge