Friday 9 June 2017

Can I keep a session alive in ssh2?

I'm trying to use node ssh2 library to create a simple program

  1. Type a command
  2. Wait for the output
  3. Type new command (Similar to putty or any ssh client)

As you can see in the example below, a new Client will be created and it will attempt connect with the specified host, right after that, over the same Client object the shell method will be called to create an interactive shell session, the shell response will contain a stream on its callback, within callback some EventEmitters are going to be added to the stream object and at the very end it will execute the stream.end('ls -l\nexit\n'); to run the command on the host side.

var Client = require('ssh2').Client;

var conn = new Client();
conn.on('ready', function() {
  console.log('Client :: ready');
  conn.shell(function(err, stream) {
    if (err) throw err;
    stream.on('close', function() {
      console.log('Stream :: close');
      conn.end();
    }).on('data', function(data) {
      console.log('STDOUT: ' + data);
    }).stderr.on('data', function(data) {
      console.log('STDERR: ' + data);
    });
    stream.end('ls -l\nexit\n');
  });
}).connect({
  host: '192.168.100.100',
  port: 22,
  username: 'frylock',
  privateKey: require('fs').readFileSync('/here/is/my/key')
});

// example output: 
// Client :: ready 
// STDOUT: Last login: Sun Jun 15 09:37:21 2014 from 192.168.100.100 
// 
// STDOUT: ls -l 
// exit 
// 
// STDOUT: frylock@athf:~$ ls -l 
// 
// STDOUT: total 8 
// 
// STDOUT: drwxr-xr-x 2 frylock frylock 4096 Nov 18  2012 mydir 
// 
// STDOUT: -rw-r--r-- 1 frylock frylock   25 Apr 11  2013 test.txt 
// 
// STDOUT: frylock@athf:~$ exit 
// 
// STDOUT: logout 
// 
// Stream :: close 

Right now my main problem is that I can't find how keep the session alive since my interpretation of the code(stream.end('ls -l\nexit\n');) is that it will run the command but as soon as it finishes the execution, the stream and the Client are going to be closed.

I found that you can pass a socket as an optional property to the connection method parameter but when I attempt to send a second command I get the following message Error: This socket is closed.

.connect({
  host: '192.168.100.100',
  port: 22,
  username: 'frylock',
  privateKey: require('fs').readFileSync('/here/is/my/key'),
  sock: mySocket
});



via Geoffrey-ap

No comments:

Post a Comment