I've written the below python class that fetches iptables rules using basic string processing in linux. Could you plz go thru it and tell me whether I'm doing this in the correct manner. I've tested the code and its running fine.
I'm ultimately going to use this class in a GUI app that I'm going to write using python+GObject.
#!/usr/bin/python
import sys, subprocess
class Fwall:
currchain=""
dichains={'INPUT':[],'OUTPUT':[],'FORWARD':[]}
dipolicy=dict(INPUT=True,OUTPUT=True,FORWARD=True)
dicolumns={}
def __init__(self):
self.getrules()
self.printrules()
print "class initialized."
def getrules(self):
s = subprocess.check_output("iptables --list --verbose",shell=True,stderr=subprocess.STDOUT)#.split('\n')
print s
for line in s.splitlines():
if len(line)>0:
self.parseline(line)
def parseline(self,line):
line=line.strip()
if line.startswith("Chain"): #this is the primary header line.
self.currchain=line.split(' ')[1]
allowed=not line.split('policy ')[1].startswith('DROP')
self.dipolicy[self.currchain]=allowed
#print "curr chain set to " + self.currchain
else:
items=line.split()
if line.strip().startswith('pkts'): #this is the secondary header line, so fetch columns.
if len(self.dicolumns)==0:
for i,item in enumerate(items):
if len(item)>0:
self.dicolumns.setdefault(item,i)
#print self.dicolumns
else:
return
else:
ditemp={}
#print line
self.dichains[self.currchain].append(ditemp)
for k,v in self.dicolumns.iteritems():
#idx= self.dicolumns[item]#,items[item]
ditemp.setdefault(k,items[v])
#print line
#print k,v
#print k,items[v]#,idx
def printrules(self):
for k,v in self.dichains.iteritems():
print k
litemp=self.dichains[k]
for item in litemp:
print item
if __name__=="__main__":
f=Fwall()