0

I'm using node to execute bash command on Linux. I need to stop and start apache server. Normally from bash you need to type:

sudo service apache2 stop

and you need to insert the password. To change that I modify the 'visudo' after modification is not asking for a password but when I run this from node I get error

Error: Command failed: /bin/sh -c sudo systemctl status apache2.service
sudo: no tty present and no askpass program specified

Where is the problem? The node code looks like that

app.get('/StatusTest', function(req, res){
    exec("sudo systemctl status apache2.service", function(err, stdout){
        if(err) throw err;
        console.log(stdout);
        res.render('statustest');
   });
})
lifeisfoo
  • 15,478
  • 6
  • 74
  • 115
cyprian
  • 497
  • 1
  • 6
  • 21
  • I also used 'sudo service apache2 stop' and 'sudo /etc/init.d/apache2 stop' but result is thesame – cyprian Sep 12 '17 at 08:49
  • Does the Node server run as the same user that you allowed passwordless access to with `visudo`? – robertklep Sep 12 '17 at 09:06
  • Yes, of course I'm running node from the same user who is in visudo – cyprian Sep 12 '17 at 09:14
  • Have you tried running `sudo systemctl status apache2.service` from a new shell to see if it _really_ doesn't ask for a password? What exactly did you add with `visudo`? – robertklep Sep 12 '17 at 09:15
  • cyprian ALL=NOPASSWD: /etc/init.d/apache2 – cyprian Sep 12 '17 at 09:16
  • But you're executing `systemctl`, not `/etc/init.d/apache2`... – robertklep Sep 12 '17 at 09:17
  • look comment above – cyprian Sep 12 '17 at 09:17
  • A number of solutions can be found in a related problem here (using the arguments -t or -A or using echo with pipe etc) : https://stackoverflow.com/questions/21659637/how-to-fix-sudo-no-tty-present-and-no-askpass-program-specified-error – Rohit Sep 12 '17 at 09:18
  • Oooo @robertklep you have right when I open new shell it's asking for a password, why is like that? – cyprian Sep 12 '17 at 09:20
  • @cyprian I guess because `sudo` doesn't think you're allowed to call it without a password (however, typically, once you entered your password you have something like 10 or 15 minutes in which subsequent calls to `sudo` will work passwordless). What you added with `visudo` _looks_ okay to me, so not sure. – robertklep Sep 12 '17 at 09:25

1 Answers1

0

You can try this command for automatic password input:

exec(`echo 'your_sudo_password' | sudo -S systemctl status apache2.service`, ...);