Skip to content Skip to sidebar Skip to footer

Running Command From Node.js With Sudo

Being new to Node.js, I have this question.. I see it mentioned in a few places that node should not be run as root, such as this. I am just using node to set up a simple web servi

Solution 1:

The hacker could do anything if there is any security issues. You could give the user witch runs the web server the permission to do the task your task is intending to do.

In general try to avoid root whenever you can (put the tinfoil hat on).

Solution 2:

According to this post from superuser of StackExchange platform, you can pipe the password to other sudo commands, like this:

echo <password> | sudo -S <command>

and according to thisStackOverflow post, you can pipe commands in spawn like this:

child.spawn('sh', args)
var args = ['-c', <the entire command you want to run as a string>];

After some hours struggling I found the solution. To wrap it all up, your answer would be something like:

import { spawn } from"child_process";
const process = spawn("sh", ["-c", "sudo -K << <password> <the entire command you want to run with sudo>"]);

I hope it would help you and others like me.

Solution 3:

Building on MajidJafari's work (which unfortunately did not work for me as he typed it) I was able to come up with something that works, albeit very convoluted.

const process = spawn("sh", ["-c", "echo <password used for sudo user> | sudo -S bash -c '<enter command or multiple commands separated by && here>'"]);

All the commands encased within the set single parenthesis ' ' will be run as sudo.

Post a Comment for "Running Command From Node.js With Sudo"