以编程方式在ssh2 nodejs中input密码

我正在使用ssh2 nodejs客户端( https://github.com/mscdex/ssh2 )

我正在尝试执行以下操作:

  1. SSH进入框。
  2. login到docker。
  3. 它会重新提示input密码。 input该密码。

我在第三步失败

这是我的代码

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!' }); 

如何以编程方式input密码? (我在做conn.exec时候已经在使用{pty: true}

请指教!

假设你的数据stream是一个双工数据stream,你可以通过写入来写入数据stream

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

或者你可以使用一个cb函数

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

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