Search code examples
node.jsshellwebstorm

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


I'm trying to run a shell script with sudo access which executes a python script using Node.js on Mac. This was a big help How to run shell script file using nodejs? but I've gotten stuck:

Shell script:

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

Node.js code:

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

When I run this in WebStorm, I am prompted to enter my password. I do so, but nothing happens; the script isn't executed. Can anybody help me with this?


Solution

  • The issue appears to be that you are not executed the node script with root permissions: sudo node filename.js.

    Furthermore, it could be that the child process you are spawning with the shelljs module does not inherit the effective UID of the parent node process. If sudo node filename.js does not solve your problem, I would recommend using the execa package instead of shelljs for better debugging and instrumentation of the spawned child-process: https://www.npmjs.com/package/execa

    You can define the uid, gid of the child process as well as the stdin stream, which you could set to ignore such that no interactive prompts can occur (the sudo command would recognize that no stdin is provided and therefore not open an interactive prompt).