Search code examples
node.jsshellsudo

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


Solution

  • 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.