当前位置:   article > 正文

监控外网IP网络的可用性及丢包率实现不重复发送报警邮件_发送邮件丢包

发送邮件丢包

重点内容
1.通过ping 来检测的网络的可用性
2.使用threading模块处理字典中的多个IP网络探测
3.为了使第二次检测故障IP,不重复发送邮件,使用redis中的列表保存已网络故障IP,当故障恢复时从redis列表中删除该故障IP

代码:

import threading
import os
import re
import smtplib
from email.mime.text import MIMEText
import redis

def send_mail(to_list, subject, content, format='plain'):
	    # 发件邮箱服务器地址
	    mail_host = 'smtp.exmail.qq.com'
	    # 邮箱用户名
	    mail_user = '发件人邮箱'
	    # 邮箱密码
	    mail_pass = 'password'
	    mail_postfix = 'exmail.qq.com'
	    me = mail_user + "<" + mail_user + "@" + mail_postfix + ">"
	    msg = MIMEText(content,format,'utf-8')
	    msg['Subject'] = subject
	    msg['From'] = me
	    msg['to'] = to_list
	    msg['Accept-Language'] = 'zh-CN'
	    msg['Accept-Charset'] = 'ISO-8859-1,utf-8'
	    try:
	        s = smtplib.SMTP()
	        s.connect(mail_host)
	        s.login(mail_user, mail_pass)
	        s.sendmail(me, to_list, msg.as_string())
	        s.close()
	        return True
	    except Exception, e:
	        print str(e)
	        return False

def ip_ping(name,ip):
	obj = re.compile(r"packets transmitted, (.*?) packet loss", re.M | re.I)
    result = os.popen('ping  -w 3 %s' % ip)
    ret = result.read()
    rs = redis.Redis(host="10.5.189.192", password="password", db=0, port=6379)
    t_tupe = obj.search(ret).groups()
    loss_precent = int(t_tupe[0].split(",")[1].strip("%"))
    print("%s:\n%s" % (name, ret))
    print("loss_precent:%d" % loss_precent)
    if loss_precent == 0:
         ret_list = rs.lrange("monitor", 0, -1)
         if ip in ret_list:
             send_mail('收件人邮箱', '【已恢复】%s服务网络故障IP:%s丢包率%s%%' % (name, ip, loss_precent), 'IP:%s' % (ip))
             rs.lrem("monitor", "%s" % ip)
    elif loss_precent > 70:
         if ip not in ret_list:
            rs.lpush("monitor", "%s" % ip)
            print("主机:%s,IP:%s,丢包率%s%%" %(name,ip,loss_precent))
            send_mail('收件人邮箱','%s服务网络故障IP:%s丢包率%s%%' %(name,ip,loss_precent),'IP:%s' %(ip))

if __name__ == "__main__":
    d = {
        "test1": "106.75.20.3",
        "test2": "106.75.9.185",
    }
    L = []
    for k in d:
        t = threading.Thread(target=ip_ping, args=(k, d[k]))
        L.append(t)
        t.start()
    [t.join() for t in L]

  • 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
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/297782
推荐阅读
相关标签
  

闽ICP备14008679号