使用具有root访问权限的nodejs执行shell命令

时间:2020-02-06 10:01:20

标签: node.js shell sudo

我想在nodeJs应用程序内执行以下shell命令。 如果我手动进行工作,则命令如下:

sudo su
password
1 command that needs a root access
exit

任何想法或代码段都会有帮助

2 个答案:

答案 0 :(得分:1)

您可以通过Ref:Super User answer

将所有4个命令组合为一个
echo "<password>" | sudo -S "<command that needs a root access>"

在您的NodeJs代码中-尝试以下操作之一:

  • 纯JS方式
var command='echo "<password>" | sudo -S "<command that needs a root access>"';
child_process.execSync(command)
  • 使用库shell-exec-使用child_process.spawn的帮助程序库
const shellExec = require('shell-exec')
var command='echo "<password>" | sudo -S "<command that needs a root access>"';
shellExec('echo Hi!').then(console.log).catch(console.log)

在触发执行之前,请确保验证需要执行的命令,以避免不必要的结果。

答案 1 :(得分:0)

您可以使用child_process的exec函数执行命令

const { exec } = require("child_process");
// Here you can execute whatever command you want to execute 
exec("ls -la", (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    // stdout returns the output of the command if you wish to use
    console.log(`stdout: ${stdout}`);
});
相关问题