Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute shell commands using nodejs with root access

I want to execute the following shell commands inside a nodeJs application. If i am doing the work manually, the commands are as following:

sudo su
password
1 command that needs a root access
exit

Any idea or a code snippet will be helpful

like image 569
Michel El Hajj Avatar asked Sep 24 '26 21:09

Michel El Hajj


1 Answers

You can combine all 4 commands into one by Ref: Super User answer

echo "<password>" | sudo -S "<command that needs a root access>"

In your NodeJs code - try one of the following:

  • Pure JS way
var command='echo "<password>" | sudo -S "<command that needs a root access>"';
child_process.execSync(command)
  • Using Library shell-exec - helper library which uses 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.

like image 175
kn_pavan Avatar answered Sep 26 '26 12:09

kn_pavan