• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

mysql 搞代码 4年前 (2022-01-09) 15次浏览 已收录 0个评论
#!/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):    '''实现发送邮件功能函数'''    _user = fromemail    _pwd  = emailpasswd    _to   = toemail    nowtime = time.strftime('%Y-%m-%d %H:%M:%S')         msg = MIMEText(msg)    msg["Subject"] = subject    <div style="color:transparent">本文来源gaodai.ma#com搞##代!^码网(</div>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 = '[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)

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python 监控日志并发送邮件报警
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址