繁体   English   中英

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

[英]Execute shell commands using nodejs with root access

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

sudo su
password
1 command that needs a root access
exit

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

您可以通过 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)

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

您可以使用 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}`);
});

虽然接受的答案很好,但它并不是最安全的 - 因为 sudo 密码以明文形式存储。

更安全的方法是在 sudoers 文件中添加一行,这将允许特定用户通过 sudo 执行特定命令而无需密码:

user host = (root) NOPASSWD: cmd

将“用户”、“主机”和“cmd”替换为您的要求。

这避免了需要以明文形式存储任何密码,并且如果您将命令封装在 shell 脚本中并进行适当的验证,则可以严格控制超级用户访问。

有关更多详细信息,请参阅此答案sudoers 手册

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM