赞
踩
重点内容
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]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。