3

使用节点 ssh2 模块,这是我需要做
的 1. 以本地用户身份 ssh 到服务器
2. sudo as oracle :sudo su oracle
3. 运行命令

我无法 sudo su oracle,因此无法运行任何命令。本地用户有权限成为 oracle,因此无需提供密码。

我可以像运行多个命令一样运行多个命令 - cd /home;./run.sh

但是如果我需要运行第一个命令是 sudo su oracle;cd /home; 的命令 ./run.sh

我没有得到回应

//代码片段

let fs = require('fs'),
  Client = require('ssh2').Client;
const executeRemote = (command, remoteServer, user, privateKey) => {
  return new Promise((resolve, reject) => {
    let conn = new Client();
    let outputData = '';
    console.log('privatekey is ' + privateKey);
    conn.on('ready', function () {
      conn.exec((command), function (err, stream) {
        if (err) {
          reject(err);
        }
        // eslint-disable-next-line no-unused-vars
        stream.on('close', function (code, signal) {
          console.log('outputData is ', outputData);
          console.log('code is ' + code);
          if (code === 0)
            resolve(outputData);
          else
            reject(outputData);

          conn.end();
        }).on('data', function (data) {
          //console.log('data is ', data.toString());
          outputData = outputData + data.toString();
        }).stderr.on('data', function (data) {
          console.log('stderr data Error- ' + data.toString());
          //check if data.toString() has WARNING
          let regex = '[WARNING]';
          if (data.toString().match(regex))
            outputData = outputData + data.toString();
          else
            reject(new Error('Failed to run the command- ' + command + ' .Error- ' + data.toString()));
        });
      });
    }).connect({
      host: remoteServer,
      port: 22,
      username: user,
      privateKey: require('fs').readFileSync(privateKey)

    });
  });
};

一旦我可以 ssh 作为本地用户,我想以 oracle 的身份运行 sudo 的命令,然后运行其他命令。是否有代码片段有人可以分享他们如何以任何用户的身份 sudo su 然后运行命令

4

1 回答 1

1

You can write the password on prompt:

ssh.exec('sudo su - ' + sudoUserName, { pty: true }, function (err, stream) {
stream.on('close', (code, signal) => {
        //clean up
}).on('data', (data) => {

    if (data.toString().substring(0, sudoUserName.length) === sudoUserName) {
        //logged in successfully
    }
    else {
        //enter password
        stream.write(password + '\n');
    }

}).stderr.on('data', (data) => {
    stream.close();
});
}
于 2020-04-16T09:03:58.053 回答