#!/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): ????'''實現(xiàn)發(fā)送郵件功能函數(shù)''' ????_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): ????'''實現(xiàn)匹配關(guān)鍵字函數(shù)''' ????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') ????#移動到文件結(jié)尾 ????f.seek(0,2) ????#讀出文件所在的字節(jié)位置 ????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?=?'服務(wù)器[%s]日志報警了!'?%?local_ip ????fromemail?=?'xxxxxxxx@qq.com' ????#emailpasswd為QQ郵箱的授權(quán)碼 ????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)
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END