Sudo command from php

I wanted to have an easy button in a webpage to restart some process that requires sudo rights. After quite some Google searches I combined a few techniques that made this work.

Although this method only grants very limited rights to the webserver, granting superrights to a web process might open up some security issues somehow. However family or co-workers simply pressing the on/off button on the server when something is not working and I’m not around is a worse problem in my opionion.

To grant the webserver the required right go to the command line and start sudo visudo.

Add following line to the file opened by the visudo command:

www-data        ALL=(ALL) NOPASSWD: /etc/init.d/asterisk restart

Where ‘www-data’ is the username your webserver is running on, ‘/etc/init.d/asterisk restart’ is the command you want to be executed.

Now create a php file asterisk.php like this:

<a href='asterisk.php?resetAsterisk=1'>Reset Asterisk</a>
<?php
if (isset($_GET['resetAsterisk'])) {
    print '<pre>';
    system('sudo /etc/init.d/asterisk restart');
    print '</pre>';
}
?>

Now restarting a process is realy just one click away!


linux