|
# coding:utf-8
"""文档说明:
该软件用于调度自动检测
1、从服务器wget调度域名列表文件
2、从文件中读取调度域名并逐个tracert
3、判断tracert结果,若路径中包含30.207.4.250表示调度正常
4、若不正常,触发告警,发出告警邮件
5、在windows的任务与计划中,每天定期执行python脚本
6、运行日志直接输出在cmd窗口(可选)
"""
#-----重要:将'节点名称'改成相应的节点名称,如nap='河北'
#----------导入模块-----------
import smtplib
import subprocess,re
from email.mime.text import MIMEText
#----------邮件发送函数-----------
def sendmail(): #定义发送邮件的函数
nap='贵州' #给本机定义个名称,用以收件人区分邮件由哪个测试机发出
sender='IpTracker2<xxxxx@163.com>' #发件人昵称及邮箱地址
receivers=['yunwei1@watone.com.cn','yunwei2@watone.com.cn','yunwei3@watone.com.cn']
subject=nap+'调度检测发现异常!!!' #邮件标题
smtpserver='smtp.163.com' #发件人邮箱smtp服务器设置
username='xxxxxx@163.com' #发件人邮箱账号
password='123456' #发件人邮箱密码
content="\n".join(detected) #列表detected中每个元素以回车分割,返回一个字符串
print ('异常内容是:'+content) #将content内容打印
msg=MIMEText(content,'text','utf-8')
msg['Subject']=subject
msg['to']=';'.join(receivers) #列表receivers元素以分号分隔
msg['from']=sender
smtp=smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username,password)
smtp.sendmail(sender,recivers,msg.as_string())
smtp.close()
#----------获取调度域名文件-----------
#下载日志记录于wgetlog.txt中,下载文件保存于c:/Python34,以diaodu.txt命令
print ("开始获取文件")
subprocess.call('wget -a wgetlog.txt -O diaodu.txt -P c:\Python34 http://1.1.1.1/diaodu.txt')
print ("文件已更新")
#----------解析调度域名,获取调度IP----------
r_getip=r'\d+\.+\d+\.+\d+\.+\d+' #定义过滤IP地址的正则表达式
file=open("c:\Python34\diaodu.txt") #打开文件
file.seek(0,0) #设置指针到行首
r_watone=r'30.207.4.250|30.207.6.154|10.30.96.10' #定义指定出口的正则表达式
detected=[]
count=1
for name in file: #遍历调度域名列表
name=name.strip('\n') #去除域名后面的\n符号,防止解析错误
resolve=subprocess.getoutput('nslookup '+name) #解析调度域名,将结果保存在resolve
track_ip=re.findall(r_getip,resolve)
track_ip.pop(0) #过滤出resolve中所有的IP地址,并删除第一个IP(第一个IP是DNS地址)
print (name+'解析成功,IP是:')
print (track_ip)
print ('开始对这些IP进行逐个检测,请耐心等候.........')
#---------跟踪调度IP并进行判断---------
for ip in track_ip: #对解析出来的IP遍历
traceroute=subprocess.getoutput('tracert -d '+ip) #保存路径跟踪结果
find=re.findall(r_watone,traceroute)
if len(find)==0: #在路径中搜索出口IP并放入列表find,若长度为0代表没从出口走
detected.append(name+"对应IP:"+ip+"检测失败!")
#将检测到域名及IP放入列表detected中
print ("第"+str(count)+"个域名检测结束!")
count+=1
#-----异常信息整理并发送告警邮件---------
try:
if len(detected)!=0: #若detected列表长度不为0,代表有域名及IP被写入
print ("有发现")
sendmail() #发送告警邮件
print ("邮件已发送!")
else:
print ("本次没有发现异常")
except Exception:
print ("程序有异常")
finally:
close=file.close() #关闭文件
if close is None:
print ("文件关闭成功,检测结束!") #确认文件关闭成功
else:
print ("文件关闭失败,请检查!") |
|
|