I am trying to extract the following data srcintf,dstintf,srcaddr,dstaddr,action,schedule,service,logtraffic from a text file and save the values into a csv file with proper rows.
The input file looks like this:
edit 258
set srcintf "Untrust"
set dstintf "Trust"
set srcaddr "all"
set dstaddr "10.2.22.1/32"
set action accept
set schedule "always"
set service "selling_soft_01"
set logtraffic all
next
edit 184
set srcintf "Untrust"
set dstintf "Trust"
set srcaddr "Any"
set dstaddr "10.1.1.1/32"
set schedule "always"
set service "HTTPS"
set logtraffic all
next
edit 124
set srcintf "Untrust"
set dstintf "Trust"
set srcaddr "Any"
set dstaddr "172.16.77.1/32"
set schedule "always"
set service "ping"
set logtraffic all
set nat enable
next
This is my first time programming (as you can see from my code) but maybe you can understand more about what I am trying to do. See code below.
import csv
text_file = open("fwpolicy.txt", "r")
lines = text_file.readlines()
mycsv = csv.writer(open('output.csv', 'w'))
mycsv.writerow(['srcintf', 'dstintf', 'srcaddr', 'dstaddr', 'schedule', 'service', 'logtraffic', 'nat'])
n = 0
for line in lines:
n = n + 1
n = 0
for line in lines:
n = n + 1
if "set srcintf" in line:
srcintf = line
else srcintf = 'not set'
if "set dstintf" in line:
dstintf = line
else dstintf = 'not set'
if "set srcaddr" in line:
srcaddr = line
else srcaddr = 'not set'
if "set dstaddr" in line:
dstaddr = line
else dstaddr = 'not set'
if "set action" in line:
action = line
else action = 'not set'
if "set schedule" in line:
schedule = line
else schedule = 'not set'
if "set service" in line:
service = line
else service = 'not set'
if "set logtraffic" in line:
logtraffic = line
else logtraffic = 'not set'
if "set nat" in line:
nat = line
else nat = 'not set'
mycsv.writerow([srcintf, dstintf, srcaddr, dstaddr, schedule, service, logtraffic, nat])
Expected results(CSV file):
srcintf,dstintf,srcaddr,dstaddr,schedule,service,logtraffic,nat
"Untrust","Trust","all","10.2.22.1/32","always","selling_soft_01",all,,
Actual results:
Traceback (most recent call last):
File "parse.py", line 45, in <module>
mycsv.writerow([srcintf, dstintf, srcaddr, dstaddr, schedule, service, logtraffic, nat])
NameError: name 'srcintf' is not defined