使用Nodejs mscdex/ssh2的root密码

fla*_*alf 7 node.js npm express

我正在尝试使用mscdex/ssh2以root身份登录远程linux机器,我试图实现的步骤是:

  1. 通过ssh连接到远程机器
  2. 以root用户身份执行命令

但我在第二部分失败了,我无法正确设置密码,这是我的代码.

  conn.on('ready', function() {
    conn.exec('sudo -s ls /', { pty: true }, (err, stream) => {
      if (err) {
       res.send(err);
      }

      stream.on('exit', (code, signal) => {
       console.log(`Stream :: close :: code: ${code}, signal: ${signal}`);
      });

      stream.on('data', data => {

        // here it's where supposedly the password should be given
        stream.write('r00tpa$$word' + '\n');
        console.log(data);
      });

    });
  }).connect({
    host: '192.168.100.100',
    username: 'fakeAdmin',
    password: 'fakePassword'
  });
Run Code Online (Sandbox Code Playgroud)

我已经将pty选项设置为true,但我只是在promt上收到错误消息.

更新:

这是我的新代码片段:

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

const encode = 'utf8';

conn.on('ready', () => {
  conn.shell(false, { pty: true }, (err, stream) => {
    if (err) { console.log(err) }

    stream.on('data', (data) => {
      process.stdout.write(data.toString(encode));
    });

    stream.write('ls -a\n');
    stream.write('uptime\n');
    stream.write('su\n'); // here nothing seems to happen
    stream.write('rootPassword\n'); // here also
    stream.write('cd /tmp && ls\n');
  });
})
.connect({
  host: "192.168.100.100",
  username: "username",
  password: "usernamePassword"
});
Run Code Online (Sandbox Code Playgroud)

我已经成功地以更清洁的方式执行了几个命令部分,我甚至在库github页面上引发了一个问题.shell命令"su"失去了交互,但现在它发生了什么它有点奇怪,我可以运行尽可能多的命令就像我什么,但是当我运行"su"命令似乎没有发生任何事情时,有人会先介入这个吗?或者我做错了什么?对不起,如果我无法解释自己的权利.

问候.

Dan*_*ola 0

考虑使用node-ssh. 我以前使用过它,没有任何问题,而且它也更现代,因为它有一个基于承诺的异步接口。

如果您需要执行 root 操作,您还应该直接连接到 root 用户,除非您的用户在执行操作时不要求输入密码sudo,例如,对于使用 Ubuntu AMI 的 EC2 实例,默认情况下,用户ubuntu无需输入密码密码(您通过 ssh 密钥对进行身份验证)。

尝试通过命令登录并以纯文本形式输入密码并不是一个好主意。还可以考虑向 root 用户添加 ssh 密钥,以使用私钥而不是密码进行身份验证。

const SSH = require('node-ssh')

const ssh = new SSH()  

ssh.connect({
  host: '<host>',
  username: 'root',
  password: '<password>'
}).then(() => ssh.exec('your command'))
Run Code Online (Sandbox Code Playgroud)