Search code examples
node.jspasswordsrootsudo

How to Set Password During Command Line Execution


I am trying to run a command line execution from Node over SSH, but am having issues running with root privileges.

const util = require('util')
const exec = require('child_process').exec

function set(pin, state) {
  exec('sudo bash -c "do something"', (error, stdout, stderr) => {
    if (error) console.log('code', error.code)
  })
}

When I try to run without the sudo command it exits with Code 1.

Since ultimately I want to run this script when an API endpoint receives a request, I would like to run this command like exec('command', 'password', (err, stdout, err)...

Can I pass in a password to the exec function to prevent a command line prompt?


Solution

  • Try this:

    echo 'password' | sudo -S command
    

    Be aware that your password will be stored in history.