Entering password programmatically in ssh2 nodejs

2019-07-31 10:59发布

问题:

I'm using ssh2 nodejs client (https://github.com/mscdex/ssh2)

I'm trying to do the following:

  1. SSH into box.
  2. Login to docker.
  3. It will re-prompt for password. Enter that password.

I'm failing on 3rd step.

This is my code

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

conn.on('ready', function() {
  console.log('Client :: ready');
  conn.exec('sudo docker ps', {pty: true}, function(err, stream) {
    if (err) throw err;
    stream.on('close', function(code, signal) {
      conn.end();

    // data comes here
    }).on('data', function(data) {
      console.log('STDOUT: ' + data);

    }).stderr.on('data', function(data) {
      console.log('STDERR: ' + data);
    });
     // stream.end(user.password+'\n'); 
     ^^ If i do this, it will work but I won't be able to do anything else afterwards

  });

}).connect({
  host: 'demo.landingpage.com',
  username: 'demo',
  password: 'testuser!'
});

How do I enter the password programmatically? (I'm already using {pty: true} while doing conn.exec

Please enlighten!

回答1:

Assuming your stream is a duplex stream, you have the possibility to write into the stream without ending it by writing

.on('data', (data) => {
   stream.write(user.password+'\n');
}

or you can use an cb function

function write(data, cb) {
  if (!stream.write(data)) {
    stream.once('drain', cb);
  } else {
    process.nextTick(cb);
  }
}

and

.on('data', (data) => {
   write(user.password+ '\n', () => {
      console.log('done');
   }
});


标签: node.js ssh