php检测服务器ip,用shell和php脚本实现定时检测服务器情况

实现原理,利用 cron来定时执行一个shell脚本,如果发现服务器不通或者上次故障后恢复正常,则发送邮件.否则不用发送邮件. 目前此Shell在FreeBSD和Linux下均可以正常运行.

ping.sh

#!/bin/bash

if [ $# -ne 1 ]

then

echo 'must have one param,must be ip address format!'

exit

fi

ip=$1

tmpfile=/tmp/$ip.txt

if [ -f $tmpfile ]; then

lastmsg=`cat $tmpfile`

else

lastmsg='YES'

fi

ret=`ping -c 3 $ip | grep ttl | wc -l`

if [ $ret -lt 2 ]; then

echo 'NO' > $tmpfile

/usr/local/bin/php /data/haohtml.com/www/ping.php $ip 0 > /dev/null 2>&1

elif [ $lastmsg = 'NO' ]; then

echo 'YES' > $tmpfile

/usr/local/bin/php /data/haohtml.com/www/ping.php $ip 1 > /dev/null 2>&1

fi

ping.php

error_reporting(7);

/* process calling arguments */

$parms = $_SERVER["argv"];

array_shift($parms);

if (!sizeof($parms)) {

exit();

}

//port num

$ip = $parms[0];

$status = $parms[1];

if ($status == 1) {

//恢复正常

$mail_msg = '恢复正常!';

} else {

$mail_msg = '无法ping通,请检查是否发生宕机情况!';

}

$mail_subject= "服务器状态检测" . $ip;//邮件主题

$mail_body='检测时间: '.date('Y-m-d H:i:s',time())."
域名/IP:$ip
状态:$mail_msg";

//发送邮件

send_mail($mail_subject, $mail_body);

/**====================================

* 邮件发送函数

* @name send_mail

* @param string $mail_subject 邮件主题

* @param string $mail_body 邮件内容

* @date 2011-07-22

* @author cfanbo

**/================================

function send_mail($mailsubject, $mailbody) {

##########################################

$smtpserver = "smtp.sina.com";

$smtpserverport = 25;

$smtpusermail = "zzwl@sina.com";

$smtpuser = "ingli";

$smtppass = "123456";

$mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件

##########################################

$email="haohtml@hotmail.com";//接收信息的邮件

include 'sendmail.class.php';

$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.

//$smtp->debug = TRUE;//是否显示发送的调试信息

$smtp->sendmail($email, $smtpusermail, $mailsubject, $mailbody, $mailtype);

//echo 'send OK';

}?>

在/etc/crontab里添加一行

*/5 * * * * root /data/ping.sh 242.28.177.171 > /dev/null 2>&1

用来每5分钟对服务器进行一次检测.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值