最近客户有一个需求要检测两台服务器之间的通信状态。要是通信是失败就需要邮件通知相关人。本来想用shell来实现,shell脚本ping 对端服务器很简单,但是shell的邮件发送比较麻烦,于是使用python实现并且用smtplib模块可以快速实现邮件的发送。
功能如下:1秒钟ping一次目标地址。代码中把你的邮箱改为自己的就可以,
代码:
#coding:utf-8 import socket import smtplib import email.MIMEText import email.Header import time import os def sendEmail(msg, passwd=‘‘, smtpAddr=‘‘ ): if type(msg[‘to‘]) == str: tos=[msg[‘to‘]] else: tos = msg[‘to‘] m = email.MIMEText.MIMEText(msg[‘content‘]) m[‘to‘] = ‘,‘.join(tos) m[‘From‘] = msg[‘from‘] m[‘Subject‘] = email.Header.Header(msg[‘subject‘], msg[‘charset‘]) m.set_charset(msg[‘charset‘]) s = smtplib.SMTP() socket.setdefaulttimeout(16) s.connect(smtpAddr) try: if passwd: s.login(msg[‘from‘].split(‘@‘)[0], passwd) return s.sendmail(msg[‘from‘], tos, m.as_string() ) finally: s.close() if __name__ == ‘__main__‘: while True: date = time.strftime(‘%Y-%m-%d %H:%M:%S‘) ip="192.168.1.1" ping= os.system("ping -c 1 %s" %ip) if ping: msg = { ‘from‘ : ‘***@***.com‘, ‘to‘ : [‘****@163.com‘], ‘charset‘ : ‘utf-8‘, ‘subject‘ : "Ping %s failed." %ip, #定义邮件主题 , ‘content‘ : "%s Ping %s failed from 255.252." % (date,ip) } sendEmail(msg, passwd=‘你的密码‘, smtpAddr=‘你的smtp服务器如:smtp.163.com‘) print "Ping %s failed,Have email." % ip else : print "Ping %s successful." % ip print "Sleep 1s..." time.sleep(1)
测试的邮件报警:
时间: 2024-11-03 22:52:23