Centos7 网络监控脚本,mail邮件告警

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

编写ping脚本检测网络状态,结合计划任务自动发送邮件告警

系统版本

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

如果不想使用系统自带邮件包,先进行删除

#rpm -qa |grep mailx sendmail
#rpm -e xxx

一、yum安装依赖包

[root@localhost ~]# yum install -y mailx
[root@localhost ~]# yum install -y sendmail
[root@localhost ~]# yum install -y sendmail-cf

二、配置sendmail.mc

[root@localhost ~]# vim /etc/mail/sendmail.mc 

把这两句开头的dnl去掉,在sendmail文件中,dnl是注释的意思,去掉dnl开启相应的设置行

改为

将此处的127.0.0.1改为0.0.0.0,意思是任意主机都可以访问sendmail服务

改为

然后保存退出

三、生成配置文件

[root@localhost ~]# m4 /etc/mail/sendmail.mc  > /etc/mail/sendmail.cf 

如果系统无法识别m4命令,则说明没有安装sendmail-cf包。m4工具在sendmail-cf包中

四、发送邮件配置

[root@localhost ~]# vim /etc/mail.rc 

在末尾添加内容,=号两边不能有空格

set from=发送人名称
set smtp=smtp.163.com
set smtp-auth-user=用户名
set smtp-auth-password=163邮箱的授权码
set smtp-auth=login

五、启动或重启sendmail

systemctl restart sendmail       #重启sendmail服务
systemctl status sendmail        #查看sendmail服务状态
systemctl enable sendmail       #设置endmail服务开机自启

六、测试

[root@localhost ~]# echo "hello world" | mail -s "test" 邮箱@qq.com

七、编写检测脚本

[root@localhost ~]# vim mail.sh
#!/bin/bash

#Network Checking script

iplist="114.114.114.114 10.1.1.1" #需要监控的IP地址池

for ip in $iplist

do

  if ping -I ens32 -c 20 $ip >iplog.txt;cat iplog.txt | grep -w '0% packet loss'
#ens32本机网卡
  then

      rm -f iplog.txt

      echo $ip line is ok 

  elif

     cat iplog.txt | grep -w '100% packet loss'

  then

      rm -f iplog.txt

      echo "$ip line is down! The time is `date`" | mail -s "Network Check Warning!"  [email protected]  #接收人邮箱

  fi

done

添加执行权限

[root@localhost ~]# chmod 777 mail.sh 

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

[root@localhost ~]# pwd
/root
[root@localhost ~]# ll
-rwxrwxrwx. 1 root root  446 Mar 22 04:32 mail.sh
[root@localhost ~]# crontab -e
*/2 * * * * /root/mail.sh

九、验证结果

猜你喜欢

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