脚本介绍
本脚本主要用于监控 LNMP 环境中的 PHP/Nginx/MySQL 服务是否可用,若不可用则写入到日志,并通过 SendMail 发送邮件进行通知!
服务器组件安装
1、sendmail安装
之前在另外一篇文章有说到过,请同学们移步官方网站看!
2、sharutils安装
Sendmail作为大多数Linux默认自带的邮件工具,把它利用起来配合做一些简单的系统管理工作,我觉得是非常好的。
之前我用sendmail每天定期将一些我需要的报告通过“正文”的方式直接发送到我的邮箱,但由于内容越来越多,看起来很不方便,如是想把这些报告通过附件的方式发送,而sendmail默认是不带有这个功能的,需要配合安装一个叫sharutils的软件包来实现。
1 2
| apt install mailutils apt install sharutils
|
3、测试组件
利用uuencode使sendmail能发送带有附件的邮件
1
| uuencode /home/wwwlogs/access.log access.log | mail -s "my lnmp log" your@mail.com
|
脚本完整代码
该 Shell 脚本已经在军哥的 LNMP 环境测试成功。
宝塔、WDCP 等搭建的可能不支持,有需要请自行修改。脚本中的收件人邮箱、监测站点的 url,请修改为你自己的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #!/bin/bash
time="$(date +"%Y%m%d-%H:%M")"
i=`netstat -an | grep php-cgi | wc -l` if [ $i = 0 ] then /etc/init.d/php-fpm restart echo "$time php-fpm service is down .... restart..." >> /var/log/php-fpm.log tail -n 20 /var/log/php-fpm.log > /root/php-mail.txt uuencode /root/php-mail.txt php-mail.txt | mail -s "$time php-fpm service restart" you@mail.com fi
i=`netstat -anpt | grep mysqld | awk '{print $4}' | awk -F: '{print $2}' | wc -l` if [ $i = 0 ] then /etc/init.d/mysql restart echo "$time mysqld service is down .... restart..." >> /var/log/mysql-error.log tail -n 20 /var/log/mysql-error.log > /root/mysql-mail.txt uuencode /root/mysql-mail.txt mysql-mail.txt | mail -s "$time Mysql service restart" you@mail.com fi
i=`netstat -anpt | grep nginx | awk '{print $4}' | awk -F: '{print $2}' | wc -l` if [ $i = 0 ] then /etc/init.d/nginx restart echo "$time nginx service is down .... restart..." >> /var/log/nginx-error.log tail -n 20 /var/log/nginx-error.log > /root/nginx-mail.txt uuencode /root/nginx-mail.txt nginx-mail.txt | mail -s "$time Nginx service service" you@mail.com fi
url=http://127.0.0.1/nginx.php i=$(curl -I -m 10 -o /dev/null -s -w %{http_code} $url) if [ $i -ne 200 ]; then /etc/init.d/mysql restart /etc/init.d/nginx restart /etc/init.d/php-fpm restart echo " $time 监测页: $url 状态码: $i 行为: 异常&重启" >> /var/log/httpcode.log fi
|
建立nginx.php文件,并且放到网站目录下
1 2 3
| < ?php echo "200_OK"; ?>
|
PHP
食用方法
1、在 root 目录下保存脚本代码,并另存为 monitor-lnmp.sh(按需自行更换名称)
2、给予文件可执行权限
1
| chmod a+x /root/monitor-lnmp.sh
|
3、加入到 crond 任务计划
执行命令 crontab -e 添加一条任务记录,例如每十分钟执行一次检测
1
| */10 * * * * bash /root/monitor-lnmp.sh
|