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

我想在 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.

https://stackoverflow.com/questions/60092266/

相关文章:

node.js - Firebase 函数错误 : The default Firebase app

sql - Oracle 12c - 插入到选择查询中的列不明确,ORA-00918

google-cloud-platform - 共享 VPC 和 VPC 对等组合

css - 如何为 Material UI 按钮 'startIcon' 分配自定义图标?

bash - 如何在 bash 中循环遍历 jq 唯一数组?

scala - 玩json库和sbt assembly合并报错

r - 确定一周中的某一天是否是 R 中每月的第 2/3 等星期一/星期二/等

arduino - ESP32 - 软件序列库

python - 如何在 XGBoost 库的 plot_tree 函数中包含特征名称?

mongodb - 使用 mongodb 中的条件将字段添加到集合