I am basically trying to continue this unanswered question about parsing a fortigate config file.
Reading a fortigate configuration file with 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. 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. 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:
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.