尝试 运行 一个 shell 脚本 node.js 使用 sudo -S

Trying to run a shell script with node.js using sudo -S

我正在尝试 运行 具有 sudo 访问权限的 shell 脚本,该脚本使用 Mac 上的 Node.js 执行 python 脚本。这是一个很大的帮助 但我被卡住了:

Shell 脚本:

#!/bin/sh
sudo -S python [pathToPythonScript]/someScripts.py

Node.js代码:

const shell = require('shelljs');
shell.exec("./[pathToShellScript]");

当我在 WebStorm 中 运行 时,系统提示我输入密码。我这样做了,但没有任何反应;脚本未执行。有人可以帮我解决这个问题吗?

问题似乎是您没有以 root 权限执行节点脚本:sudo node filename.js

此外,您使用 shelljs 模块生成的子进程可能没有继承父节点进程的有效 UID。 如果 sudo node filename.js 不能解决你的问题,我建议使用 execa 包而不是 shelljs 来更好地调试和检测生成的子进程:https://www.npmjs.com/package/execa

您可以定义子进程的uidgid以及stdin流,您可以将其设置为ignore这样就不会出现交互提示( sudo 命令会识别出没有提供 stdin,因此不会打开交互式提示)。