Centos7 系统服务监控脚本,mail邮件告警

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tladagio/article/details/88786340

编写脚本检测应用服务状态,结合计划任务自动发送邮件告警

系统版本

[root@localhost ~]# cat /etc/redhat-release 
CentOS Linux release 7.6.1810 (Core) 

一、根据需求安装应用服务,实验安装http做测试

[root@localhost ~]# yum install -y httpd

二、启动服务,注意查看服务器状态,脚本需要用到

[root@localhost ~]# systemctl start httpd
[root@localhost ~]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: active (running) since Mon 2019-03-25 09:52:34 CST; 8s ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 8922 (httpd)
   Status: "Processing requests..."
   CGroup: /system.slice/httpd.service
           ├─8922 /usr/sbin/httpd -DFOREGROUND
           ├─8923 /usr/sbin/httpd -DFOREGROUND
           ├─8924 /usr/sbin/httpd -DFOREGROUND
           ├─8925 /usr/sbin/httpd -DFOREGROUND
           ├─8926 /usr/sbin/httpd -DFOREGROUND
           └─8927 /usr/sbin/httpd -DFOREGROUND

Mar 25 09:52:34 localhost.localdomain systemd[1]: Starting The Apache HTTP Server...
Mar 25 09:52:34 localhost.localdomain httpd[8922]: AH00558: httpd: Could not reliably determine the server's fully qualified doma...essage
Mar 25 09:52:34 localhost.localdomain systemd[1]: Started The Apache HTTP Server.
Hint: Some lines were ellipsized, use -l to show in full.

案例一:

一、编写检测脚本

[root@localhost ~]# vim httpd.sh
#!/bin/bash
#this is httpd service script
name1="running"
name2="dead"


if systemctl status httpd | grep $name1

then

    echo "system httpd service is start!" | mail -s "Service check OK" 邮箱@qq.com

elif
    systemctl status httpd | grep $name2

then

    echo "system http service is stop!" | mail -s "Service check Warring" 邮箱@qq.com
fi

添加执行权限

[root@localhost ~]# chmod +x httpd.sh 
[root@localhost ~]# ll
-rwxr-xr-x. 1 root root  362 Mar 25 09:50 httpd.sh

二、添加计划任务,每隔两分钟检测一次

[root@localhost ~]# crontab -e
*/2 * * * * /root/httpd.sh

三、检测正常

四、手动停止httpd,查看告警

案例二:

一、添加脚本,尽量别取和http同名,要不ps检测结果不准确

扫描二维码关注公众号,回复: 6711589 查看本文章
[root@localhost ~]# vim test.sh 
#!/bin/bash

#记录日志文件
LOG_FILE="autostart.log"

#系统时间
curtime=$(date "+%Y-%m-%d %H:%M:%S")

#检测进程
pnhttp=`ps -ef | grep http | grep -v "grep" | wc -l`


if [ $pnhttp -eq 0 ]; then
        echo "$curtime 系统检测到http,已挂掉" >> autostart.log;
        echo "system httpd is down,尝试自动恢复" | mail -s "Service check http" 邮箱@qq.com;

#尝试启动httpd
	    systemctl start httpd;
else
        echo "$curtime 系统检测到http运行正常" >> autostart.log;
	echo "system httpd is up" | mail -s "Service check http" 邮箱@qq.com;
fi

添加执行权限

[root@localhost ~]# chmod +x test.sh 

二、添加计划任务,时间根据需要调整

[root@localhost ~]# crontab -e
*/2 * * * * /root/test.sh

三、检测正常

四、手动停止httpd,查看告警

自动恢复成功

猜你喜欢

转载自blog.csdn.net/tladagio/article/details/88786340