-
-
Save xoxefdp/a2f4ba2ad365b73c5e0d636b92e036b3 to your computer and use it in GitHub Desktop.
SSH Interactive shell session in Node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment