Tuesday, August 16, 2011

PHP - Monitoring server down


I wrote a script test_cron.php below to monitor the web servers. If a web server is down, an email notification will be sent to me. A windows task scheduler is used.
To start task scheduler in Windows 7:
1. Go to Start > Programs > Accessories > System Tools > Task Scheduler
2. Click "Create Task" in right panel.
3. Click "General" to set task name; click "trigger->new" to set how often task happens; click "action->new", Program\Script: "C:\Program Files (x86)\Mozilla Firefox\firefox.exe" and Add argument: http://localhost:8082/test_cron.php.
4, Cilck OK.

My test_cron.php:
$servers = array(1 => "cesei.org",
2 => "acseper.facs.org");
$i=0;
foreach($servers as $key => $value){

$site = $value;
$port = '80';
$check = fsockopen( $site, $port, $errno, $errstr, 10);
$downurl=" ";
if (!$check){
$i=$i+1;
$downurl .= $value.', ';
}
}


$mail = new PHPMailer();

$mail->IsSMTP(); // set mailer to use SMTP
$mail->From = "myname@gmail.com";
$mail->FromName = "myname";
$mail->Host = "smtp.gmail.com"; // specif smtp server
$mail->SMTPSecure= "ssl"; // Used instead of TLS when only POP mail is selected
$mail->Port = 465; // Used instead of 587 when only POP mail is selected
$mail->SMTPAuth = true;
$mail->Username = "myname@gmail.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
$mail->AddAddress("myname@gmail.com", "myname"); //replace myname and mypassword to yours
$mail->AddReplyTo("myname@gmail.com", "myname");
$mail->WordWrap = 50; // set word wrap
//$mail->AddAttachment("c:\\temp\\js-bak.sql"); // add attachments
//$mail->AddAttachment("c:/temp/11-10-00.zip");

$mail->IsHTML(true); // set email format to HTML
$mail->Subject = 'Server '.$downurl.' down';
$mail->Body = 'Server '.$downurl.' down';

if($i>0){
if($mail->Send()) {echo "Send mail successfully";}
else {echo "Send mail fail";}
}
else echo "Server OK";
?>

No comments:

Post a Comment