selvan
selvan

Reputation: 1243

How to disconnect ssh connection by using node-ssh in 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.

Upvotes: 7

Views: 9115

Answers (5)

M Shahzeb Raza
M Shahzeb Raza

Reputation: 63

So what worked for me was basically destroying the ssh-client's connection before disposing the connection. Take a look at the following code

    // Create an SSH Client
    const ssh = new NodeSSH();
    
    // Establish a connection to the ssh server
    const connection = await ssh.connect({
        username: 'username', // username of the main server
        host: 'ipaddress', // ip address of the main server
        password: 'password'
    })


    // Run the command on the ssh server
    const response = await connection.execCommand('commandToRun')
    console.log('Response: ', response.stdout)

    if (connection.isConnected()) console.log('🔥 Connection is alive; Disposing the connection')
    // destroy the ssh client connection
    ssh.connection?.destroy()
    // dispose the connection
    connection.dispose()

    if (!connection.isConnected()) console.log('Connection is successfully disposed')

You should see the following logs:

🔥 Connection is alive; Disposing the connection
✅ Connection is successfully disposed

Upvotes: 1

Brance Lee
Brance Lee

Reputation: 150

I struggle for these the ssh to a remote server frequently, and the connection can not be closed by ssh.compose() in the ssh-node package, and I find remote windows ssh server still generate many processes named sshd process and not be closed, and after ssh.compose, the node.js will throw the error Error: read ECONNRESET at TCP.onStreamRead which can not be caught by code.I find many references, it could be the TCP connection is still working on and not be closed. So I try to refer to the ssh-node code and use the

ssh.connection.destroy()

which point to the Client.prototype.destroy method in ssh2 package, so the error Error: read ECONNRESET at TCP.onStreamRead will disappeared, and the connection will be closed totally.

Upvotes: 0

bersling
bersling

Reputation: 19302

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();
});

Upvotes: 15

SharpEdge
SharpEdge

Reputation: 1762

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();

Upvotes: 2

Cody Haines
Cody Haines

Reputation: 1235

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.

Upvotes: 4

Related Questions