class to check if servers are down
Posted: Sat Oct 21, 2006 9:11 pm
This following class will check X amount of servers to see if they can be pinged. If the ping request reports anything other than a 0% loss of packets, you will be emailed alerting you that that server may be down. You should set this on a shedule to run every X minutes.
I tested this on Windows. Whether or not it would work on a linux server, I don't know.
I'm going to configure mine to TXT my cell phone, but I figure i'd produce something useful while I was at it! So here it is:
The Code
The Test
The Output (emails that it sent)
I tested this on Windows. Whether or not it would work on a linux server, I don't know.
I'm going to configure mine to TXT my cell phone, but I figure i'd produce something useful while I was at it! So here it is:
The Code
Code: Select all
<?php
/* This class will check X amounts of servers to see if they can be pinged.
* If they can't be pinged, or ping reports more than a 0% loss of packets,
* you will be emailed.
*
* author: scottayy@gmail.com
*/
class serverup
{
var $servers = array();
var $output;
//add a server ip to be tested
//@param string $server_ip
function add_server($server_ip)
{
$this->servers[] = $server_ip;
}
//check if up
//@param string $email
function check($email)
{
foreach($this->servers AS $server)
{
//check if output array is empty
if(!empty($this->output))
{
$this->output = array();
}
//execute ping
exec('ping '.$server, $this->output);
//check the output
if($percent_loss = $this->check_output())
{
if($percent_loss !== true)
{
$msg = 'Server '.$server.' may be down. Ping is reporting a '.$percent_loss.'% ' .
'loss of packets on '.date("n-d-Y \a\\t g:i A").".\n";
}
} else
{
$msg = 'Server '.$server.' may be down. Ping reports it to be unreachable on '.
date("n-d-Y \a\\t g:i A").".\n";
}
//mail results if server may be down
if(!empty($msg))
{
mail($email, $subject='Server May Be Down', $msg);
}
}
}
//checks ping result for % of lost pings
function check_output()
{
$output = implode("\n", $this->output);
if(preg_match("/([\d]{1,3})% loss/", $output, $matches))
{
if($matches[1] > 0)
{
return $matches[1];
} else
{
return true;
}
} else
{
return false;
}
}
}Code: Select all
$serverup = new serverup();
$serverup->add_server('1.1.1.1');
$serverup->add_server('1.1.1.1.1.1.1');
$serverup->check('you@email.com');Code: Select all
Server 1.1.1.1 may be down. Ping is reporting a 100% loss of packets on 10-22-2006 at 11:09 PM.Code: Select all
Server 1.1.1.1.1.1.1 may be down. Ping reports it to be unreachable on 10-22-2006 at 11:09 PM.