The other day I decided that the little ‘Network Monitor’ desktop gadget I was using to monitor my few servers just wasn’t cutting it. Instead, I wanted to make use of a spare iMac and have something a little flashier. A Google search for Server Monitors brought up a plethora of options that were either horribly ugly, platform specific, or just didn’t work the way I needed (most required that the target server be running some form of web server, such as IIS or Apache to retrieve headers to see if the server was up – most of my servers don’t run those). As such, I decided to write a small script from scratch.
I figured the easiest way to accomplish my goal of a platform-independent monitoring script was to use PHP. After enabling Apache2/PHP5 on my Snow Leopard-running iMac (a topic for another blog post later), I searched through the PHP.net function list until I found fsockopen(). This function is quite ideal, as it will work with any open port. The first step was to make a quick function to utilize fsockopen and return some testable results:
function checkServer($ip,$port){$fp = fsockopen($ip,$port,$errno,$errstr,1);if (!$fp){return ‘Down’;} else {return ‘Up’;}}
I added this to a <?php ?> block in the <head></head> of the document – to call the function and perform the test, I used the following line below:
$servername = checkServer(’192.168.1.100′,’53′);
In this example I’m checking the availability of a DNS server, so I use port 53. When this runs, the $servername is set to either ‘Up’ or ‘Down’ depending on whether or not a connection can be opened on that port.
The only thing left now was to display this output. I made a fancy table-based page with graphics where each server is a cell and the background changes between green and red depending on the $servername value. However, all you really need is the code below in a <?php ?> block in the body of the page:
echo(‘Server Example Status: ‘.$servername);
Changing Example to the name of your server. If you have more than one server to check, just make another variable, use the checkServer function to give it a value (make sure to change the IP address and use an open port!), and then add another echo line.
That’s it! To be fancy, you can add a javascript automagic page refresh to – just change the <body> tag to:
<body onLoad=”Javascript:timedRefresh(30000); display();”>
And put the following in the <head></head> section:
<script type=”text/Javascript”>
<!–
function timedRefresh(timeoutPeriod) {
setTimeout(“location.reload(true);”,timeoutPeriod);
}
// –>
</script>
And you’re done! If the server is up, every 30 seconds your page will refresh and show:
Server Example Status: Up









