码迷,mamicode.com
首页 > 移动开发 > 详细

nagios-plugin(log)

时间:2014-09-27 18:37:00      阅读:361      评论:0      收藏:0      [点我收藏+]

标签:python   nagios   

#!/usr/bin/env python

import datetime
import re 
import sys

REG_SYSLOG = re.compile(r‘(?P<logtime>\w+ \d+ [\d:]+) (?P<hostname>[\d\w.]+) (?P<progname>\w+)(\[\d*\])?: (?P<msg>.*)‘)

DELTA = datetime.timedelta(minutes=3)

MONTH_MAPPING = {"Jan":1,"Feb":2,"Mar":3,"Apr":4,"May":5,"Jun":6,"Jul":7,"Aug":8,"Sep":9,"Oct":10,"Nov":11,"Dec":12}

PROG_COUNTER = {}
KEYWORD_COUNTER = {}

KEYWORD = [‘error‘,‘fatal‘]

def parsertime(s):
    month, day, t = s.split()
    hour, minute, second = [int(i) for i in t.split(‘:‘)]
    return datetime.datetime(2014,MONTH_MAPPING[month],int(day),hour,minute,second)

def count(metric, counter):
    if metric in counter:
        counter[metric] += 1
    else:
        counter[metric] = 1

def getMessages():
    starttime = datetime.datetime.now() - DELTA
    logfile = ‘/var/log/messages‘
    with open(logfile) as fd:
        for line in fd:
            logmatch = REG_SYSLOG.match(line)
            if logmatch:
                logdict = logmatch.groupdict()
                logtime = parsertime(logdict[‘logtime‘])
                if logtime >= starttime:
                    count(logdict[‘progname‘], PROG_COUNTER)
                    for k in KEYWORD:
                        if k in logdict[‘msg‘].lower():
                            count(k, KEYWORD_COUNTER)

def print_msgs(status,msgs):
    mapping = {0:‘OK‘,1:‘Warning‘,2:‘Critcal‘,3:‘Unknown‘}
    msg = ‘%s:%s‘ % (mapping[status],‘ | ‘.join(msgs))
    print msg
    sys.exit(status)

def check_counter():
    msgs = []
    status = 0
    if PROG_COUNTER:
        for c in PROG_COUNTER:
            if PROG_COUNTER[c] > 2:
                msgs.append("prog %s has reached %s " % ( c, PROG_COUNTER[c]))
                status = 2
            elif PROG_COUNTER[c] <= 2:
                msgs.append("prog %s has reached %s " % ( c, PROG_COUNTER[c]))
                status = 1
    if KEYWORD_COUNTER:
        status = 2
        msgs.append("keywords have reached %s" % ‘,‘.join([‘%s:%s‘%(k,KEYWORD_COUNTER[k]) for k in KEYWORD_COUNTER]))
    print_msgs(status, msgs)

if __name__ == ‘__main__‘:
    getMessages()
    check_counter()

本文出自 “muzinan的技术博客” 博客,谢绝转载!

nagios-plugin(log)

标签:python   nagios   

原文地址:http://muzinan110.blog.51cto.com/684213/1558811

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!