您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

python 监控日志并发送邮件报警

2024/8/23 7:14:30发布47次查看
#!/usr/bin/env python #coding:utf8 import re import os import time import smtplib import socket import fcntl import struct from email.mime.text import mimetext def get_ip_address(ifname): s = socket.socket(socket.af_inet, socket.sock_dgram) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # siocgifaddr struct.pack('256s', ifname[:15]) )[20:24]) def sendemail(subject,msg,fromemail,emailpasswd,toemail): '''实现发送邮件功能函数''' _user = fromemail _pwd = emailpasswd _to = toemail nowtime = time.strftime('%y-%m-%d %h:%m:%s') msg = mimetext(msg) msg["subject"] = subject msg["from"] = _user msg["to"] = _to try: s = smtplib.smtp_ssl('smtp.qq.com', 465) s.login(_user, _pwd) s.sendmail(_user, _to, msg.as_string()) s.quit() print "[%s]info:email send success!" % nowtime except smtplib.smtpexception,e: print "[%s]error:email send falied,%s" % (nowtime,e) def matchkeyword(pattern,alertlogfile): '''实现匹配关键字函数''' re.compile(pattern) posfile = "/tmp/posfile" if not os.path.exists(posfile): os.mknod(posfile) if not os.path.getsize(posfile): with open(posfile,'w') as fobj: fobj.write('0') #打开文件 f = open(alertlogfile,'r') #移动到文件结尾 f.seek(0,2) #读出文件所在的字节位置 endpos = f.tell() #移动到文件的开头 with open(posfile,'r') as fobj: startpos = int(fobj.read()) f.seek(startpos) if endpos-startpos > 0: data = f.read(endpos-startpos) f.close() with open(posfile,'w') as fobj: fobj.write(str(endpos)) m = re.findall(pattern, data,re.ignorecase) if m: content = '\n'.join(m) return content else: return '' if __name__ == '__main__': local_ip = get_ip_address('eth0') subject = '服务器[%s]日志报警了!' % local_ip fromemail = 'xxxxxxxx@qq.com' #emailpasswd为qq邮箱的授权码 emailpasswd = 'mdkuasfhnjbrbhdj' toemail = 'xxxxxx@qq.com' alertlogfile = "/data/mysql/mysql_3306/log/error.log" #pattern = ".*\[warning\].*\s|.*\[note\].*\s" pattern = ".*warning.*\s|.*error.*\s" while true: content = matchkeyword(pattern, alertlogfile) if content: sendemail(subject, content, fromemail, emailpasswd, toemail)
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product