Search code examples
phplinuxrebootsunatty

Use shell_exec() to restart server?


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?


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');