使用Python读取配置文件 [英] Reading a fortigate configuration file with Python

查看:77
本文介绍了使用Python读取配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

针对长期以来提出的问题的应用程序.

Appologies for the really long drawn out question.

我正在尝试读取配置文件并获取规则列表. 我尝试使用ConfigParser来执行此操作,但这不是标准的配置文件. 该文件不包含节头,也不包含令牌.

I am trying to read in a config file and get a list of rules out. I have tried to use ConfigParser to do this but it is not a standard config file. The file contains no section header and no token.

config部分
设置其他内容
配置小节A
将此设置为
下一个
结束

config section a
set something to something else
config subsection a
set this to that
next
end

配置防火墙策略
编辑76
将srcintf设置为那里"
将dstintf设置为此处"
将srcaddr设置为全部"
将dstaddr设置为全部"
设定动作接受
设置时间表总是"
设置服务"TCP_5600"
下一个
编辑77
将srcintf设置为此处"
将dstintf设置为有"
将srcaddr设置为全部"
将dstaddr设置为全部"
设定动作接受
设置时间表总是"
设置服务"PING"
下一个
结束

config firewall policy
edit 76
set srcintf "There"
set dstintf "Here"
set srcaddr "all"
set dstaddr "all"
set action accept
set schedule "always"
set service "TCP_5600"
next
edit 77
set srcintf "here"
set dstintf "there"
set srcaddr "all"
set dstaddr "all"
set action accept
set schedule "always"
set service "PING"
next
end

由于我无法确定如何使ConfigParser正常工作,我以为我会尝试遍历该文件,但是不幸的是,我没有太多的编程技能,所以被卡住了. 我真的认为我正在使这一过程变得比应有的复杂. 这是我编写的代码;

As I couldn't work out how to get ConfigParser to work I thought I would try to iterate through the file, unfortunately I don't have much programming skill so I have got stuck. I really think I am making this more complicated than it should be. Here's the code I have written;

class Parser(object):

    def __init__(self):
        self.config_section = ""
        self.config_header = ""
        self.section_list = []
        self.header_list = []

    def parse_config(self, fields): # Create a new section
        new_list = []
        self.config_section = " ".join(fields)
        new_list.append(self.config_section)

        if self.section_list: # Create a sub section
            self.section_list[-1].append(new_list)
        else: self.section_list.append(new_list)

    def parse_edit(self, line): # Create a new header
        self.config_header = line[0]
        self.header_list.append(self.config_header)

        self.section_list[-1].append(self.header_list)  

    def parse_set(self, line): # Key and values
        key_value = {}

        key = line[0]
        values = line[1:]
        key_value[key] = values

        if self.header_list:
            self.header_list.append(key_value)
        else: self.section_list[-1].append(key_value)

    def parse_next(self, line): # Close the header
        self.config_header = []

    def parse_end(self, line): # Close the section
        self.config_section = []

    def parse_file(self, path):
        with open(path) as f:
            for line in f:

                # Clean up the fields and remove unused lines.            
                fields = line.replace('"', '').strip().split(" ")

                if fields[0] == "set":
                    pass
                elif fields[0] == "end":
                    pass
                elif fields[0] == "edit":
                    pass
                elif fields[0] == "config":
                    pass
                elif fields[0] == "next":
                    pass
                else: continue

                # fetch and call method.
                method = fields[0]
                parse_method = "parse_" + method

                getattr(Parser, parse_method)(self, fields[1:])
                return self.section_list

config = Parser().parse_file('test_config.txt')

print config

我正在寻找的输出类似于以下内容;

The output I am looking for is something like the following;

[['a部分,{'something':'到其他东西'}},['subsection a',{'this':'to that'}]],['防火墙政策',['76 ',{'srcintf':'There'},{'dstintf':'Here'} {etc.} {etc.}]]]

[['section a', {'something': 'to something else'}, ['subsection a', {'this': 'to that'}]],['firewall policy',['76',{'srcintf':'There'}, {'dstintf':'Here'}{etc.}{etc.}]]]

这就是我得到的

[[''a section']]

[['section a']]

编辑

我更改了以上内容以反映我现在的位置. 我在获得期望的输出时仍然遇到问题.我似乎无法正确列出清单.

I have changed the above to reflect where I am currently at. I am still having issues getting the output I expect. I just can't seem to get the list right.

推荐答案

我将我的答案发布给试图解析Fortigate配置文件时首先来自Google的人们! 我根据自己的需要重写了在这里找到的内容,效果很好.

I post my answer for people who first come here from Google when trying to parse Fortigate configuration file ! I rewrote what I found here based on my own needs and it works great.

from collections import defaultdict
from pprint import pprint
import sys

f = lambda: defaultdict(f)

def getFromDict(dataDict, mapList):
    return reduce(lambda d, k: d[k], mapList, dataDict)

def setInDict(dataDict, mapList, value):
    getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value    

class Parser(object):

    def __init__(self):
        self.config_header = []
        self.section_dict = defaultdict(f)     

    def parse_config(self, fields): # Create a new section
        self.config_header.append(" ".join(fields))

    def parse_edit(self, line): # Create a new header
        self.config_header.append(line[0])

    def parse_set(self, line): # Key and values
        key = line[0]
        values = " ".join(line[1:])
        headers= self.config_header+[key]
        setInDict(self.section_dict,headers,values)

    def parse_next(self, line): # Close the header
        self.config_header.pop()

    def parse_end(self, line): # Close the section
        self.config_header.pop()

    def parse_file(self, path):          
        with open(path) as f:
            gen_lines = (line.rstrip() for line in f if line.strip())
            for line in gen_lines:
               # pprint(dict(self.section_dict))
                # Clean up the fields and remove unused lines.            
                fields = line.replace('"', '').strip().split(" ")

                valid_fields= ["set","end","edit","config","next"]
                if fields[0] in valid_fields:
                    method = fields[0]
                    # fetch and call method
                    getattr(Parser, "parse_" + method)(self, fields[1:])

        return self.section_dict

config = Parser().parse_file('FGT02_20130308.conf')

print config["system admin"]["admin"]["dashboard-tabs"]["1"]["name"]
print config["firewall address"]["ftp.fr.debian.org"]["type"]

这篇关于使用Python读取配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆