Sunday, April 8, 2012

Shutdown an internal server with a php page.

A more efficient way is posted on my more recent post .

For some reason, don't ask me why, it was very useful to me to shutdown a server using a http-request. This way I didn't have to go to the server to shut him down which is handy if it is locked away. Only for boot up I have to access the machine.

Pre-requisite is off course that a webserver is running on the machine, as there are plenty of tutorials to setup an Apache server I am not going to address that here.

Concept of the solution


In my solution I will be running a simple script every minute to check if a file exists. I the file exists, the script will remove the file and will shutdown the server, if not the script will do nothing. The reason I chose this solution is because it doesn't require much work :-).

The script


The content of the script is:

#!/bin/bash
if [ -f /tmp/shutdown ]
then
echo "HttpServerShutdown script called" >> /var/log/syslog
/bin/rm /tmp/shutdown
/sbin/shutdown -h now
fi

This script is saved as /var/remoteShutdown.sh. It is important to use the full path to the commands. If you use just the command it is probably not part of the path and it will not execute properly.

Trigger the script every minute.


We want to execute the script every minute. Luckily Linux has something like cronjobs. Because we use the shutdown command which should be executed with appropriate privileges, we will set cronjobs with sudo. To do this execute:
 sudo crontab -e 
If you have never added a cronjob, you can chose an editor to use. As I am a vi fan I use vi but if you don't know via chose another one :-). Nano is rather straightforward. Using the text editor append a line with the following content:

 * * * * * /var/remoteShutdown.sh


Make sure you save the crontab file.

PHP-page


As I have a default installation of Apache, my PHP pages are kept in /var/www. Create a file called shutdown.php with the following contents:

<?
echo "shutdown";
$file=fopen("/tmp/shutdown",'w');
fwrite($file,"pretty please");
fclose($file);
?>


That's it. Now you can browse to http://<serverIP>/shutdown.php and your server will shutdown.

2 comments:

  1. #!/bin/bash
    if [ -f /tmp/shutdown ]
    then
    echo "HttpServerShutdown script called" >> /var/log/syslog
    /bin/rm /tmp/shutdown
    /sbin/shutdown -h now
    fi

    ReplyDelete
  2. https://www.instagram.com/dieva.03

    ReplyDelete