beginerdeveloper beginerdeveloper - 17 days ago 8
Node.js Question

node js set timeout in ssh in ssh2

How can I set a timeout for the connection to a ssh server?

Currently, I am connecting to the server with the following code:

var Client = require('ssh2');

var conn = new Client();
conn.on('ready', function(){
console.log("connected");
});
conn.on('error', function(){
console.log("fails");
});
conn.connect({
host: ip,
port: 22,
username: user,
password: password
});

Answer

You can set readyTimeout in the connect options like this :

conn.connect({
    host: ip,
    port: 22,
    username: user,
    password: password,
    readyTimeout: 5000
});

This will cancel any connection that is not ready within 5 seconds.

You can read more about it in the documentation of ssh2.