I have a webserver that also plays internet radio. As www-data user I want to run some commands, for example I've made this in /etc/sudoers file:
www-data ALL=(ALL) NOPASSWD: /usr/bin/amixerAnd form PHP I can manipulate volume without using password by:
exec('sudo -u user amixer set Master 3%-');And:
exec('sudo -u user amixer set Master 3%+');But now I want to be able to restart my own service by runing command:
exec('sudo -u user service servicename restart');So I tried:
www-data ALL=(ALL) NOPASSWD: /usr/bin/amixer, NOPASSWD: /bin/serviceAnd this:
www-data ALL=(ALL) NOPASSWD: /usr/bin/amixer, /bin/serviceAnd even this:
www-data ALL=(ALL) NOPASSWD: /usr/bin/amixer
www-data ALL=(ALL) NOPASSWD: /bin/serviceBut none of them seems to be working. Please help me out.
Sorry guys - my mistake. I've done some changes, tried to link form /sbin to /bin
Now I have changed it to:
www-data ALL=(ALL) NOPASSWD: /usr/bin/amixer, NOPASSWD: /usr/sbin/serviceAnd it works! Thanks! Topic closed.
52 Answers
Careful with your solution: you can start, stop or restart any service that way!
Better create a shell script that runs this command:
echo "#!/bin/sh' > /usr/bin/amixer_restart
echo "sudo -u user service amixer restart' >> /usr/bin/amixer_restartGrant adequate permissions (550 mean root and group www-data can read and execute, nobody can write)
sudo chown root:www-data /usr/bin/amixer_restart
sudo chmod 550 /usr/bin/amixer_restartAnd allow apache to sudo on this script:
www-data ALL=(ALL) NOPASSWD: /usr/bin/amixer_restart This is what I ended up doing:
- Install apache2 by running
sudo apt-get install apache2 - Make sure apache is allowed to run cgi scripts by running
sudo a2enmod cgi - Restart apache
sudo service apache2 restart Verify that I can run bash scripts by creating the following script at
/usr/lib/cgi-bin/test.sh#!/bin/bash # get today's date OUTPUT="$(date)" USR=$(whoami) # headers echo "Content-type: text/plain" echo "" # body echo "Today is $OUTPUT" echo "Current user is $USR"make the script executable
chmod +x /usr/lib/cgi-bin/test.shVerify I am able to execute the script
curl localhost/cgi-bin/test.shI get back the following response:Today is Wed Sep 6 12:19:34 PDT 2017 Current user is www-dataBecause the user is www-data I then add that user as a sudoer. I then modify the file
/etc/sudoersby adding this line at the end:www-data ALL=(ALL) NOPASSWD: ALLNow that user is supposed to have root privileges. Then I modify my test.sh script as:
#!/bin/bash # get today's date OUTPUT="$(date)" USR=$(sudo whoami)Then you should see the following response when executing a get request agains
localhost/cgi-bin/test.sh:Today is Wed Sep 6 12:28:38 PDT 2017 Current user is root