在 ssh2 nodejs 中以编程方式输入密码 [英] Entering password programmatically in ssh2 nodejs

查看:79
本文介绍了在 ssh2 nodejs 中以编程方式输入密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

I'm trying to do the following:

  1. SSH 进入盒子.
  2. 登录 docker.
  3. 它会重新提示输入密码.输入那个密码.

我在第三步失败了.

这是我的代码

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

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

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

请赐教!

推荐答案

假设你的 stream 是一个双工流,你有可能在不通过写入结束的情况下写入流

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

或者你可以使用 cb 函数

or you can use an cb function

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

这篇关于在 ssh2 nodejs 中以编程方式输入密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆