首页 > 代码库 > python运维----检测主机IP ping不通则发邮件

python运维----检测主机IP ping不通则发邮件

第一章:对ip.txt文件中IP地址进行ping操作,对于ping不通的,发送邮件至对应的邮箱

 1 #!/usr/bin/env python3 
 2 #coding: utf-8
 3 
 4 #第一步:将对应的iping不通的p地址弄到noping.txt文件中
 5 
 6 import commands
 7 import os
 8 import smtplib 
 9 import email.MIMEMultipart# import MIMEMultipart 
10 import email.MIMEText# import MIMEText 
11 import email.MIMEBase# import MIMEBase 
12 import mimetypes 
13 import email.MIMEImage
14 import MIMEImage
15 
16 f = open("/lianxi/aochuanfei/ip.txt","r")
17 f_noping_ip = open("/lianxi/aochuanfei/noping.txt","w")
18 
19 for ip in f.readlines():
20     # 此处必须对IP地址进行处理--将ip地址转换为字符串,否则getstatusoutput函数里面不能传入变量
21     os.environ[ip] = str(ip)
22 
23     # 判断ping 一下IP 之后是否通的并返回状态的语句
24     (status, optput) = commands.getstatusoutput(ping -c 2 $ip)
25 
26     # 判断返回的状态,如果为0说明ping得通,如果不为0则将对应的IP地址写入另外一个文件里面,然后通过右键发送
27     if status != 0:
28         # print status,‘The ip was not ping tong is‘,ip
29         # 状态为0的的直接pass
30         f_noping_ip.write(str(ip))
31     else:
32         # print status,‘The ip was ping de tong is‘,ip
33         # 状态不为0的全部写入到noping.txt文件里面
34         pass
35 
36 f.close()
37 f_noping_ip.close()
38 
39 #第二步:将文件noping.txt通过邮件发送到对应邮箱
40 
41 
42 From = "aochuanfei@163.com" 
43 To = "1585051879@qq.com" 
44 file_name = "noping.txt"#附件名 
45 
46 server = smtplib.SMTP("smtp.163.com") 
47 server.login("aochuanfei","aixocm123") #仅smtp服务器需要验证时 
48 
49 # 构造MIMEMultipart对象做为根容器 
50 main_msg = email.MIMEMultipart.MIMEMultipart() 
51 
52 # 构造MIMEText对象做为邮件显示内容并附加到根容器 
53 text_msg = email.MIMEText.MIMEText("this is a test text to text mime",_charset="utf-8") 
54 main_msg.attach(text_msg) 
55 
56 # 构造MIMEBase对象做为文件附件内容并附加到根容器 
57 ctype,encoding = mimetypes.guess_type(file_name) 
58 if ctype is None or encoding is not None: 
59     ctype=application/octet-stream 
60 maintype,subtype = ctype.split(/,1) 
61 file_msg=email.MIMEImage.MIMEImage(open(file_name,rb).read(),subtype) 
62 print ctype,encoding 
63 
64 ## 设置附件头 
65 basename = os.path.basename(file_name) 
66 file_msg.add_header(Content-Disposition,attachment, filename = basename)#修改邮件头 
67 main_msg.attach(file_msg) 
68 
69 # 设置根容器属性 
70 main_msg[From] = From 
71 main_msg[To] = To 
72 main_msg[Subject] = "ping不通的IP地址请看附件" 
73 main_msg[Date] = email.Utils.formatdate( ) 
74 
75 # 得到格式化后的完整文本 
76 fullText = main_msg.as_string( ) 
77 
78 # 用smtp发送邮件 
79 try: 
80     server.sendmail(From, To, fullText) 
81 finally: 
82     server.quit()

 

python运维----检测主机IP ping不通则发邮件