人气旺 发表于 2014-9-28 09:19:22

nagios-plugin(log)

#!/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 =
    return datetime.datetime(2014,MONTH_MAPPING,int(day),hour,minute,second)

def count(metric, counter):
    if metric in counter:
      counter += 1
    else:
      counter = 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,' | '.join(msgs))
    print msg
    sys.exit(status)

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

if __name__ == '__main__':
    getMessages()
    check_counter()
页: [1]
查看完整版本: nagios-plugin(log)