经常遇到系统 load average因某些原因突然飙涨到上百,以致系统假死。故根据飞信的php接口写了一个监控程序。当系统平均负载超过某个flag时,自动发短信到我手机上通知我。
要求:1、开启php的系统调用函数,注意,这有一定的安全隐患。
2、拥有飞信的账号,确切点说就是使用中国移动!
3、能操作shell
注:本系统使用的是centos
附件里有整个程序及Fetion类下载,有兴趣的请便
<?php
/**
* @author blvming
* @link http://www.sphinxsearch.org
* @todo 本程序用于检测linux/unix系统负载,并对超过限定值时发送短信通知管理员
* @copyright copyleft
* @example crontab : * /2 * * * * /usr/bin/php /webserver/chkload.php ; 每2分钟检测一次
* @warning 注意防火墙要打开 https(443)端口,另外还需要注意php的安全模式,能让php调用系统函数
* @version 1.0
*
*
*/
set_time_limit(360); //多则无益
error_reporting(0);
define(‘ALERT’,10);//普通警告
define(‘CRASH’,30); //系统非常卡,即将假死崩溃
define(‘INTERVAL’,450); //发送的间隔时间(秒),防止飞信一直发短信骚扰,
define(‘MAXCOUNT’,5); //出现问题后发送短信的最多次数。如,短信发送超过5次后会自动停止发送
$mobile = ’158****8169′;//你的移动手机
$password = ‘passwd’ ;//飞信密码
//查看并返回系统负载
$loadStr = system(‘uptime’,$load);
//格式化返回值
$loadArr = explode(" ",$loadStr);
//取5分钟内的负载均值为判断标志
$flag = (float)$loadArr[13];
if($flag < ALERT) exit; //没事就别发骚扰短信^_^
//加载飞信类,并登录飞信
require_once(‘fetion.class.php’);
$fetion = new fetion() ;
$fetion->sign_in ($mobile, $password) ; //手机号和飞信密码
//计数器,防止系统一直发送短信
$counterFile = dirname(realpath(__FILE__)).’/counter’; //计数器文件
if(!file_exists($counterFile))
{
file_put_contents($counterFile,”);
}
//序列化存储,取出数据后还原
$counterArr = unserialize(file_get_contents($counterFile));
if(is_array($counterArr))
{
if((time() – $counterArr['timestamp']) < INTERVAL) exit(); //小于间隔时间,则退出
if($counterArr['counter']>=MAXCOUNT) exit(); //发送次数超过 5次就不用发送了
}
//警告
if($flag > ALERT and $flag < CRASH)
{
$msg = ‘警告:系统负载超过’.ALERT."\n详细:".$loadStr;
}
else if($flag > CRASH) {
$msg = ‘系统即将卡死:’.$loadStr;
}
$fetion->send_sms($mobile,$msg) ;
$counterArr['counter']++;
$counterArr['timestamp'] = time();
//计数序列化后写入文件
file_put_contents($counterFile,serialize($counterArr));
exit();
?>