I have scripts in /etc/init.d/
that I use to control game servers and I would like to build a simple web interface to call those scripts. My sudoers file contains something like
www-data ALL=(ALL) NOPASSWD: /etc/init.d/starbound start stop
When I execute sudo /etc/init.d/starbound start
within PHP, nothing happens. Am I missing something? Trying to access paths my PHP user is not allowed to usually gives me the appropriate warnings at least.
Seems the problem lies in the sudoers file. If I remove the start stop
, it works.
So a correct sudoers could look like this:
Cmnd_Alias GAMES = /etc/init.d/ark_thecenter start, \
/etc/init.d/ark_thecenter stop, \
/etc/init.d/ark_theisland start, \
/etc/init.d/ark_theisland stop, \
/etc/init.d/starbound start, \
/etc/init.d/starbound stop
www-data ALL=(ALL) NOPASSWD: GAMES
Using sudo
requires that you input your password when you run a command. By running sudo
with exec()
you aren't providing the password to sudo
and cannot run the command with root level privileges.
Ubuntu.SE provides a way to pass the password to sudo in a single command, but the result is a little messy when implemented with PHP because the Password:
prompt will be sent to STDOUT when the call is made, but that can be silenced by sending the output to /dev/null
. The result of the command can still be stored in a variable as you might expect.
<?php
//Kill a sudo session if one exists.
exec('sudo -k');
//Run sudo without authenticating
$output = exec('sudo echo "foo"');
var_dump($output); //string(0) ""
//Provide the password and pipe it into sudo.
$output = exec('echo "password" | sudo -S echo "foo" 2> /dev/null');
var_dump($output); //string(3) "foo"
?>