Enter sudo password after running Spawn command

Asked

Viewed 50 times

3

I’m trying to make a script on Node.js to update my computer.

I’m using child_process.spawn.

When typing sudo apt update, it keeps waiting for the password. I have tried to inform with stdin.write, but I was unsuccessful.

PS: It has to be with sudo.

var spawn = require('child_process').spawn;
    app.post('/update',cors(), function (req, res) {
        let command = `sudo apt udpate'`
        const cmd = spawn(command,[], { shell: true });

        cmd.stdin.write("minhasenha\n");


        cmd.stdout.on('data', (data) => {
            // cmd.stdin.write("minhasenha");
            console.log(`stdout: ${data}`);
        });
    })

1 answer

1

The sudo directly access the tty to which you are connected to receive the password, and so it is no use to write it in stdin.

To work around this you can add a permission to the file sudoers to execute the desired command without password:

  1. execute the command visudo
  2. add the line seu-usuário ALL=NOPASSWD:/usr/bin/apt
  3. save the change and close the editor

After that the seu-usuário can execute the command sudo apt <argumentos> without ever asking for the password again.

If you modify the sudoers is not possible, you can use the argument --askpass plus the environment variable SUDO_ASKPASS to specify a command that would provide the password via stdout.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.