我想在 nodeJs 应用程序中执行以下 shell 命令。如果我手动进行工作,命令如下:
sudo su
password
1 command that needs a root access
exit
任何想法或代码片段都会有所帮助
您可以通过参考将所有 4 个命令合二为一:超级用户答案
echo "<password>" | sudo -S "<command that needs a root access>"
在您的 NodeJs 代码中 - 尝试以下操作之一:
var command='echo "<password>" | sudo -S "<command that needs a root access>"';
child_process.execSync(command)
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
将 'user'、'host' 和 'cmd' 替换为您的要求。
这避免了将任何密码以明文形式存储的需要,并且如果您将命令包装在带有适当验证的 shell 脚本中,则可以严格控制超级用户访问。
有关更多详细信息,请参阅此答案或sudoers 手册