我想在 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)
Be sure to validate the command that need to be executed, before triggering execute to avoid unwanted results.
关于node.js - 使用具有 root 访问权限的 nodejs 执行 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60092266/