情景:web监控时,若匹配出相应关键字时,把匹配的相关内容放入redis数据库。redis数据库内随着时间推移是不断增加的。
功能:实现当redis数据库里的数据增加时,想用户发送一封邮件,提醒查看。
代码:
# -*- coding: UTF-8 -*- ‘‘‘ @note: 实现对redis数据库监控功能,有变化发送邮件 ‘‘‘ import redis import time import smtplib from email.mime.text import MIMEText red=redis.StrictRedis("172.16.2.156",6379,8) mailto_list=[‘1234567@qq.com‘] #邮件接收方 mail_host="smtp.163.com" #设置邮件服务器 mail_user="abcd" #用户名 mail_pass="abcd123" #口令 mail_postfix="163.com" #发件箱的后缀 def send_mail(to_list,sub,content): me="scan_result"+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEText(content,_subtype=‘plain‘,_charset=‘gb2312‘) msg[‘Subject‘] = sub msg[‘From‘] = me msg[‘To‘] = ";".join(to_list) try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user,mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False def loop(): lis=red.hgetall(‘alert‘).values() num=len(lis) time.sleep(10) lis=red.hgetall(‘alert‘).values() num_2=len(lis) if num==num_2: print ‘no new keyword added......‘ else: if send_mail(mailto_list,"keywords","there have a keyword added ,please check inredis databases......"): print "send email success......" else: print "send email false......" if __name__ == ‘__main__‘: while True: try: loop() except: continue
本文出自 “黑色时间” 博客,请务必保留此出处http://blacktime.blog.51cto.com/11722918/1795312
原文地址:http://blacktime.blog.51cto.com/11722918/1795312