Tag:python monitoring logging
#!/usr/bin/env python#coding:utf8import reimport osimport timeimport smtplibimport socketimport fcntlimport structfrom email.mime.text import mimetextdef 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): ' Implement Send mail function ' ' _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&Nbsp;matchkeyword (Pattern,alertlogfile): "Implement match keyword function" ' 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 = ' server [ %s] Log Alarm! ' % local_ip fromemail = ' [email protected] ' #emailpasswd为QQ邮箱的授权码 emailpasswd = ' MDKUASFHNJBRBHDJ ' toemail = ' [email protected] ' 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)
After this script is started, error.log is monitored, and if a warning,error keyword is found, the information in this line is sent to the specified mailbox as the message body.
This article is from the "Xu Mingjiang blog" blog, make sure to keep this source http://dadaloveyou.blog.51cto.com/703960/1878222
Python monitors logs and sends mail alerts