Python 100 project #30: Fortigate Policy to CSV

Today I made a script it takes fortigate config, and make a csv file for firewall policies.

If I use API, it can be much easier, as it does not require any data transformation required to collect those data. But still there are lots of cases (and most of the cases for me) the API is not enabled on the unit. In those cases, I need to use text based config file to make a parameter sheet.

 

Output Example:

>>> from fortigate_helper import policy_to_dict
>>> from helper.dict_helper import to_csv
>>> 
>>> policies = policy_to_dict('data_source/fg_sample_config.txt')
>>> 
>>> to_csv(policies, 'data_out/fg_sample_policies.csv')

 

Here is the code:

def policy_to_dict(file):
    from collections import defaultdict

    parameters = [
        "srcintf",
        "dstintf",
        "srcaddr",
        "dstaddr",
        "service",
    ]

    policy_dict = defaultdict(dict)

    policy_statements = []

    with open(file, "r") as f:
        in_policy = False
        for line in f:
            line = line.strip()
            # check if it's under 'config firewall policy' section. Emit 'next' also.
            if in_policy and line != "next":

                if line == "end":
                    break
                policy_statements.append(line)

            else:
                if line == "config firewall policy":
                    in_policy = True

    if policy_statements:

        for statement in policy_statements:
            op, param, *val = statement.split()
            if op == "edit":
                policy_id = param
            elif op == "set" and param in parameters:
                policy_dict[policy_id][param] = ' '.join(val)

    return policy_dict