Created
August 9, 2017 14:30
-
-
Save wolkenarchitekt/6e8aa105c5f644fd3803f8b41dcbe4f3 to your computer and use it in GitHub Desktop.
Parse Icinga object cache file using Python and regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Parse Icinga object cache file into proper data structure | |
import re | |
import logging | |
logger = logging.getLogger(__name__) | |
def parse_config(cache_file): | |
""" | |
Parse Icinga object cache | |
:param cache_file: Object cache file | |
:return: list containing dictionaries for each object | |
""" | |
content = open(cache_file).read() | |
regex = r'define\s+(\w+)\s+\{\n|\t(\w+)\s+([^\n]*)\n|\t\}' | |
matches = re.finditer(regex, content, re.DOTALL) | |
result = [] | |
obj = {} | |
key = None | |
for match in matches: | |
groups = match.groups() | |
if groups == (None, None, None): | |
result.append(obj) | |
obj = {} | |
for group_num in range(0, len(groups)): | |
group_num = group_num + 1 | |
if match.group(group_num): | |
token = match.group(group_num) | |
logger.info("Group {}: {}".format(group_num, token)) | |
if group_num == 1: | |
obj['object_type'] = token | |
elif group_num == 2: | |
key = token | |
elif group_num == 3: | |
obj[key] = token | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment