Automate Ubuntu Server Shutdown

power downSomebody on the Ubuntu Forums was asking how to get their server to shut down automatically when no other computers are online on the network.  This can be useful if you have Wake-On-Lan enabled on the server, and you're only using it for things like printer or file sharing.  I responded with a little php script I whipped up that does the job nicely.

You will need the php package and the nmap package to make this work

sudo apt-get install php nmap

Next, you'll need to know how to setup a cron job.  If you don't, check out this tutorial.

Here is the contents of the php file.
hostsup.php
 

<?php
// Call the nmap command
$output shell_exec('nmap -sP 192.168.1.*');

// Split up the output so we get the number of hosts up
$split1 explode("addresses ("$output);
$split2 explode(" hosts up"$split1[1]);
$hostsup $split2[0];

// If only x number of computer are on + router, shutdown.  Take in account the server being a computer!
if($hostsup == "2") {
    
$shutdown shell_exec('shutdown -h now');
}
?>

You'll need to edit the "192.168.1.*" to fit your network's IP range.  Also, change the $hostsup == "2" to the number of computers you want on when it shuts down.  The server counts as one, your router counts as one, and if you have any of those network printers, they also count.  If it gets an IP, count it.  Feel free to change the shutdown command to something else if you want to put the server into standby or what have you.

In your cron job, just set the command as

php -f /path/to/file/hostsup.php

Set the cron to run as often as you like.  I'd set it for every half-hour just to not use up too many resources, and still be effective.

What this script is doing is executing "nmap -sP 192.168.1.*".  This generates a list of nodes on the network that are currently online, and their IP addresses.  The next 3 lines parse through the information to only get the number of nodes online.  Next we check how many are online, if the numbers match then execute the shutdown command.  You'll need root or sudo access to use the shutdown command, so watch out.