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

标签 node.js shell sudo

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

相关文章:

node.js - 使用 node-imap 与 Gmail 的非 SSL 连接

linux - 查找当前路径的深度

ubuntu - 如何克服在 VPS 上设置 Github Actions 配置时出现的 "Must not with Sudo"错误

c - 如何在 C 中实现我自己的基本 unix shell?

java - 如何在linux中通过java执行shell脚本并保存在文本文件命令中

python - 在 Python 中使用 Paramiko 模块切换到 root 用户时获取 "must be run from a terminal"

python - sudo 和 pip 不在同一条路径上

ios - React native 错误 AppRegistry 未定义?

node.js - 在 NodeJS 中异步使用同步进程

Javascript, Promise.then 返回值