有时候php业务的网站突然无法访问,我们会去查找原因,首先会判断是不是web服务器挂了,然后再去查询是不是数据库挂了,这里提供一个脚本自动去检测是web服务器和数据库服务器,去确定到底是哪个服务器挂掉,并自动去启动相对应的服务!
# vi check.sh
#!/bin/sh cd /usr/local/sbin test -e "checkweb.php" && rm -rf checkweb.php test -e "checkdb.php" && rm -f checkdb.php test -e "wget-log" && rm -f wget-log test -e "wget-log.1" && rm -f wget-log.1 wget -b "http://127.0.0.1/checkweb.php" > /dev/null 2>&1 wget -b "http://127.0.0.1/checkdb.php" > /dev/null 2>&1 sleep 2 checkweb=`cat checkweb.php` checkdb=`cat checkdb.php` if [ "$checkweb" == "ok" ] ;then echo "`date +%d/%m/%Y:%H:%M:%S` - - Webserver successfully!" if [ "$checkdb" == "ok" ] ;then echo "`date +%d/%m/%Y:%H:%M:%S` - - Mysql connected successfully!" echo " " echo "-------------------------------------------------------------" elif [ "$checkdb" != "ok" ] ;then /etc/init.d/mysqld restart echo "`date +%d/%m/%Y:%H:%M:%S` - - Mysql connected bad!restart successful!" curl "http://sms.api.bz/fetion.php?username=150********&password=******&sendto=150********&message=php连接数据库失败,数据库重启成功!" echo " " echo "-------------------------------------------------------------" fi exit 0 elif [ "$checkweb" != "ok" ] ;then killall -9 nginx /usr/local/nginx/sbin/nginx /usr/local/php-fcgi/sbin/php-fpm restart echo "`date +%d/%m/%Y:%H:%M:%S` - - Webserver is down!restart successfully!" wget -b "http://127.0.0.1/checkdb.php" > /dev/null 2>&1 sleep 2 checkdb2=`cat checkdb.php` if [ "$checkdb2" == "ok" ] ;then echo "`date +%d/%m/%Y:%H:%M:%S` - - Mysql connected successfully!" curl "http://sms.api.bz/fetion.php?username=150********&password=******&sendto=150********&message=php服务器down机,重启成功!" echo " " echo "-------------------------------------------------------------" elif [ "$checkdb2" != "ok" ] ;then /etc/init.d/mysqld restart echo "`date +%d/%m/%Y:%H:%M:%S` - - Mysql connected bad!restart successful!" curl "http://sms.api.bz/fetion.php?username=150********&password=******&sendto=150********&message=php服务器,mysql服务器down机,重启成功!" echo " " echo "-------------------------------------------------------------" fi exit 0 fi |
checkweb.php内容:
<?php echo "ok"; ?>; |
checkdb.php内容:
<?php //测试php数据库链接状态的脚本 $mysql_user = "dbuser"; $mysql_password = "dbpwd"; $link = mysql_connect("localhost",$mysql_user,$mysql_password) or die("bad"); print ("ok"); mysql_close($link); ?> |
#crontab -e */2 * * * * /usr/local/sbin/check.sh >> /var/log/check.log |