[英]Parsing a Fortigate config file with Python
I am basically trying to continue this unanswered question about parsing a fortigate config file. 我基本上是试图继续这个关于解析配置文件的未回答的问题。
Reading a fortigate configuration file with Python 使用Python读取配置文件
The root problem is that this config contains a number of records like this, 根本问题是此配置包含许多这样的记录,
edit 1
set srcintf "port26"
set dstintf "port25"
set srcaddr "all"
set dstaddr "all"
set action accept
set utm-status enable
set schedule "always"
set service "ANY"
set av-profile "default"
set nat enable
set central-nat enable
next
I would like to get the output for each acl on a single line so I can import them into a CSV. 我想在一行上获取每个acl的输出,以便将其导入CSV。 The problem is that each record can have a variable number of lines, and the indentation shows subsections of the preceding line.
问题在于每个记录可以具有可变数量的行,并且缩进显示前一行的小节。 The other post does get some of it correctly, but it doesn't handle the indentation.
另一篇文章确实正确地获得了其中的一部分,但它不处理缩进。 I have come up with some workarounds that replace white spaces with arbitrary characters, but I didn't know if there was a method to read the number tabs/whitespaces and use that to indicate positioning.
我想出了一些用任意字符替换空格的解决方法,但是我不知道是否有一种方法可以读取数字制表符/空格并将其用于指示位置。
Thanks 谢谢
So I have managed to read your text and turn it into a dictionary in python. 因此,我设法阅读了您的文本并将其转换为python中的字典。 It is pretty simple.
这很简单。 You basically have to do something along the lines of:
您基本上必须按照以下方式进行操作:
conFigFile=open('./config.txt')
data=dict()
record=0
for line in conFigFile:
if line.find('edit')>=0:
record=int(line.replace('edit',''))
data[record]={}
if line.find('set')>=0:
line=line.replace('set','')
line=line.strip()
print line
key,val=line.split(' ')
data[record][key]=val
conFigFile.close()
This will produce a dictionary which will then allow you to make calls such as: 这将产生一个字典,然后将允许您进行如下调用:
>>> data[1]['nat']
'enable'
>>> data[1].keys()
['nat', 'service', 'schedule', 'central-nat', 'srcaddr', 'av-profile', 'dstintf', 'srcintf', 'action', 'dstaddr', 'utm-status']
So now it is possible to generate a csv file: 因此,现在可以生成一个csv文件:
csvFile=open('./data.csv','w')
records=data.keys()
for record in records:
values=data[record].keys()
valList=['Record',str(record)]
for val in values:
valList.append(val)
valList.append(data[record][val])
csvFile.write(",".join(valList))
csvFile.close()
Which produces the csv file: 生成csv文件:
Record,1,nat,enable,service,"ANY",schedule,"always",central-nat,enable,srcaddr,"all",av-profile,"default",dstintf,"port25",srcintf,"port26",action,accept,dstaddr,"all",utm-status,enable
If you really want to count the spaces before the line, you can do something like the following: 如果您真的想计算行前的空格,可以执行以下操作:
>>> a=' test: one '
>>> a.count(' ') #count all spaces
11
>>> (len(a) - len(a.lstrip())) #count leading spaces
5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.