Use shell_exec() to restart server?
Question
I have a 128MB VPS and every now and then it gets cluttered. Rebooting will fix the issue but what if I want to reboot from the browser (password-protected page). How can "www-data" restart my machine (Natty Narwhal) by using PHP's shell_exec()
function?
I am confused because it requires sudo. The thing is I am never logged in as www-data, will it be my sudo password? Also how would I include a password to execute this?
Would using root work? If so then how would I do su from www-data?
La solution
You are correct that the shutdown
script requires root, or sudo, privileges to be executed. If you really need to reboot your server through a web-accessible page, one way to do this would be to add www-data
to the sudoers list, but only for access to the shutdown
command.
Edit /etc/sudoers
and add the following line:
%www-data ALL=NOPASSWD: /sbin/shutdown
The line will allow the www-data
group to have access to sudo /sbin/shutdown
without the need for a password - so make sure that your web-accessible script isn't public.
After editing the sudoers file, you can use the following from your script to reboot:
shell_exec('sudo /sbin/shutdown -r now');
Autres conseils
Another way you could do this is to have a root cron job that runs every few minutes, checking for a file. If it finds the file, it removes it and reboots the system. Your web page just needs to create the file.
How about using RSA keys with SSH tunnel?
You could generate www-data user an RSA key and SSH -i to another user (root) with it, provided that you add the public key to the other user's authorized hosts file. Then you won't need passwords as long as you do interactive SSH with your key.
You may want to examine your exact needs, and make sure this is not a security risk and fits your situation, but this is the first thing that came to my mind.
Hope it helps!