How to parse nagios status.dat file?

前端 未结 7 1127
一生所求
一生所求 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:46

    You can do something like this:

    def parseConf(filename):
        conf = []
        with open(filename, 'r') as f:
            for i in f.readlines():
                if i[0] == '#': continue
                matchID = re.search(r"([\w]+) {", i)
                matchAttr = re.search(r"[ ]*([\w]+)=([\w\d]*)", i)
                matchEndID = re.search(r"[ ]*}", i)
                if matchID:
                    identifier = matchID.group(1)
                    cur = [identifier, {}]
                elif matchAttr:
                    attribute = matchAttr.group(1)
                    value = matchAttr.group(2)
                    cur[1][attribute] = value
                elif matchEndID:
                    conf.append(cur)
        return conf
    
    def conf2xml(filename):
        conf = parseConf(filename)
        xml = ''
        for ID in conf:
            xml += '<%s>\n' % ID[0]
            for attr in ID[1]:
                xml += '\t%s\n' % \
                        (attr, ID[1][attr])
            xml += '\n' % ID[0]
        return xml
    

    Then try to do:

    print   conf2xml('conf.dat')
    

提交回复
热议问题