监控服务器网络是否正常
功能:监控服务器网络是否正常(比如网线松动)或者服务器启动是否正常,如果服务器异常,邮件通知。
1 #encoding:utf-8 2 ''' 3 Created on 2016-2-18 4 5 @author: yuanyuan 6 ''' 7 from email.mime.text import MIMEText 8 from email.utils import formatdate 9 import smtplib 10 import os 11 import time 12 13 class Email: 14 def __init__(self, from_addr, from_password, to_addrs): 15 self.from_addr = from_addr 16 self.from_password = from_password 17 self.to_addrs = to_addrs 18 19 def send_mail(self, message): 20 smtp_server = 'smtp.sihuatech.com' 21 # 邮件正文,html格式 22 html = '<html><body><h2><font color="#FF0000">' + str(message) + '</font></h2></body></html>' 23 msg = MIMEText(html, 'html', 'utf-8') 24 # 发件人 25 msg['From'] = self.from_addr 26 # 收件人 27 msg['To'] = ";".join(self.to_addrs) 28 # 主题 29 msg['Subject'] = message[9:23] + "服务器异常" 30 # 时间 31 msg['Date'] = formatdate(localtime=True) 32 try: 33 server = smtplib.SMTP(smtp_server, 25) 34 server.login(self.from_addr, self.from_password) 35 server.sendmail(self.from_addr, self.to_addrs, msg.as_string()) 36 except Exception, e: 37 print e 38 finally: 39 server.close() 40 41 if __name__ == '__main__': 42 from_addr = 'fayuan.peng@sihuatech.com' 43 from_password = '1qaz@WSX' 44 to_addrs = ['fayuan.peng@sihuatech.com', 'chang.lu@sihuatech.com'] 45 serviers = ['10.222.138.210', '10.222.138.232', '10.222.138.233', '10.222.138.128', '10.222.138.118'] 46 47 email_realtimeMonotor = Email(from_addr, from_password, to_addrs) 48 49 while True: 50 for servier in serviers: 51 response_message = os.system('ping -c 4 ' + servier) 52 if response_message > 0: 53 print '服务器异常,需要发送邮件' 54 if servier == "10.222.138.210": 55 email_realtimeMonotor.send_mail("真实机10.222.138.210异常,可能导致虚拟机10.222.138.221、10.222.138.223、10.222.138.225、10.222.138.227、10.222.138.228、10.222.138.229、10.222.138.230、10.222.138.231无法访问,请检查网线是否松动或者机器是否正常启动") 56 elif servier == "10.222.138.232": 57 email_realtimeMonotor.send_mail("真实机10.222.138.232异常,可能导致虚拟机10.222.138.238、10.222.138.243、10.222.138.247、10.222.138.248无法访问,请检查网线是否松动或者机器是否正常启动") 58 elif servier == "10.222.138.233": 59 email_realtimeMonotor.send_mail("真实机10.222.138.233异常,可能导致虚拟机10.222.138.236、10.222.138.245、10.222.138.246无法访问,请检查网线是否松动或者机器是否正常启动") 60 elif servier == "10.222.138.128": 61 email_realtimeMonotor.send_mail("真实机10.222.138.128异常,可能导致虚拟机10.222.138.110、10.222.138.111、10.222.138.112、10.222.138.113、10.222.138.116、10.222.138.117、10.222.138.123、10.222.138.124无法访问,请检查网线是否松动或者机器是否正常启动") 62 elif servier == "10.222.138.118": 63 email_realtimeMonotor.send_mail("真实机10.222.138.128异常,请检查网线是否松动或者机器是否正常启动") 64 else: 65 print '服务器正常,无需发送邮件' 66 time.sleep(5) 67 time.sleep(600)