標籤:python nagios
#!/usr/bin/env pythonimport datetimeimport re import sysREG_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] = 1def 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)