Skip to content

Instantly share code, notes, and snippets.

@roccomuso
Created April 20, 2017 13:56
Show Gist options
  • Save roccomuso/9e7328d855ec97e0226e6e8cb036b09a to your computer and use it in GitHub Desktop.
Save roccomuso/9e7328d855ec97e0226e6e8cb036b09a to your computer and use it in GitHub Desktop.
SSH Interactive shell session in Node.js
var Client = require('ssh2').Client;
var readline = require('readline')
var conn = new Client();
conn.on('ready', function() {
console.log('Client :: ready');
conn.shell(function(err, stream) {
if (err) throw err;
// create readline interface
var rl = readline.createInterface(process.stdin, process.stdout)
stream.on('close', function() {
process.stdout.write('Connection closed.')
console.log('Stream :: close');
conn.end();
}).on('data', function(data) {
// pause to prevent more data from coming in
process.stdin.pause()
process.stdout.write(data)
process.stdin.resume()
}).stderr.on('data', function(data) {
process.stderr.write(data);
});
rl.on('line', function (d) {
// send data to through the client to the host
stream.write(d.trim() + '\n')
})
rl.on('SIGINT', function () {
// stop input
process.stdin.pause()
process.stdout.write('\nEnding session\n')
rl.close()
// close connection
stream.end('exit\n')
})
});
}).connect({
host: 'localhost',
port: 22,
username: 'myUser',
password: 'PASSWORD' // or provide a privateKey
});
@wmertens
Copy link

wmertens commented Sep 8, 2020

even simpler, no readline needed: https://stackoverflow.com/a/63793635/124416

@roccomuso
Copy link
Author

Interesting use of setRawMode, I'm wondering if that could help fixing this issue roccomuso/netcat#11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment