How to parse nagios status.dat file?

前端 未结 7 1130
一生所求
一生所求 2020-12-21 02:06

I\'d like to parse status.dat file for nagios3 and output as xml with a python script. The xml part is the easy one but how do I go about parsing the file? Use multi line re

7条回答
  •  既然无缘
    2020-12-21 02:37

    Having shamelessly stolen from the above examples, Here's a version build for Python 2.4 that returns a dict containing arrays of nagios sections.

    def parseConf(source):
        conf = {}
        patID=re.compile(r"(?:\s*define)?\s*(\w+)\s+{")
        patAttr=re.compile(r"\s*(\w+)(?:=|\s+)(.*)")
        patEndID=re.compile(r"\s*}")
        for line in source.splitlines():
            line=line.strip()
            matchID = patID.match(line)
            matchAttr = patAttr.match(line)
            matchEndID = patEndID.match( line)
            if len(line) == 0 or line[0]=='#':
                pass
            elif matchID:
                identifier = matchID.group(1)
                cur = [identifier, {}]
            elif matchAttr:
                attribute = matchAttr.group(1)
                value = matchAttr.group(2).strip()
                cur[1][attribute] = value
            elif matchEndID and cur:
                conf.setdefault(cur[0],[]).append(cur[1])              
                del cur
        return conf
    

    To get all Names your Host which have contactgroups beginning with 'devops':

    nagcfg=parseConf(stringcontaingcompleteconfig)
    hostlist=[host['host_name'] for host in nagcfg['host'] 
              if host['contact_groups'].startswith('devops')]
    

提交回复
热议问题