Skip to content

Instantly share code, notes, and snippets.

@paolorossi
Last active August 29, 2015 14:21
Show Gist options
  • Save paolorossi/90a19bf632092396065f to your computer and use it in GitHub Desktop.
Save paolorossi/90a19bf632092396065f to your computer and use it in GitHub Desktop.
Node.js: retry SSH connection after error (with timeout)
// npm install ssh2
var Client = require('ssh2').Client;
var cmd = 'tail -f /tmp/foo.log';
var TIMEOUT = 5000;
var host = {
host: 'host.example.com',
port: 22,
username: 'username',
password: 'password'
}
// Init all stuff
var connected = false;
var conn = new Client();
conn.on('ready', function() {
connected = true;
console.log('Client :: ready');
conn.exec(cmd, function(err, stream) {
if (err) throw err;
stream.on('close', function(code, signal) {
console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
conn.end();
}).on('data', function(data) {
console.log('STDOUT: ' + data);
}).stderr.on('data', function(data) {
console.log('STDERR: ' + data);
});
})
}).on('error', function(data) {
connected = false;
console.log('ERROR: ' + data);
})
// Try first connect
conn.connect(host);
// Handle connection retries
setInterval(function() {
if (!connected) {
console.log('Trying to connect...')
conn.connect(host);
}
}, TIMEOUT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment