使用具有 root 访问权限的 nodejs 执行 shell 命令
Execute shell commands using nodejs with root access
我想在 nodeJs 应用程序中执行以下 shell 命令。
如果我手动完成工作,命令如下:
sudo su
password
1 command that needs a root access
exit
任何想法或代码片段都会有所帮助
您可以通过参考将所有 4 个命令合并为一个:Super User answer
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)
Be sure to validate the command that need to be executed, before triggering execute to avoid unwanted results.
您可以使用 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 脚本中并进行适当的验证,则可以严格控制超级用户访问。
有关详细信息,请参阅 this answer or the sudoers manual
我想在 nodeJs 应用程序中执行以下 shell 命令。 如果我手动完成工作,命令如下:
sudo su
password
1 command that needs a root access
exit
任何想法或代码片段都会有所帮助
您可以通过参考将所有 4 个命令合并为一个:Super User answer
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)
Be sure to validate the command that need to be executed, before triggering execute to avoid unwanted results.
您可以使用 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 脚本中并进行适当的验证,则可以严格控制超级用户访问。
有关详细信息,请参阅 this answer or the sudoers manual