Reputation: 1101
Been working on parsing iptables output to get the stats per source IP usin python. Did not want to include iptc module. So just doing string manipulations.
bytes target prot opt in out source destination
0 0 udp -- * eth1 10.10.10.10 0.0.0.0/0 udp spt:10
0 0 tcp -- * eth1 10.10.10.10 0.0.0.0/0 tcp spt:10
0 0 all -- * eth1 1.1.1.1 0.0.0.0/0
0 0 all -- * eth1 0.0.0.0/0 0.0.0.0/0 source IP range 5.5.5.5-5.5.5.10
0 0 all -- * eth1 0.0.0.0/0 0.0.0.0/0 source IP range 4.4.4.4-4.4.4.5
0 0 all -- * eth1 0.0.0.0/0 0.0.0.0/0
>>> s=' 0 0 udp -- * eth1 10.10.10.10 0.0.0.0/0 udp spt:10 '
>>> s.split()
['0', '0', 'udp', '--', '*', 'eth1', '10.10.10.10', '0.0.0.0/0', 'udp', 'spt:10']
want to parse as below, how do I seperate all the spaces except single space between words ?
expected_output=['0', '0', 'udp', '--', '*', 'eth1', '10.10.10.10', '0.0.0.0/0', 'udp spt:10']
OR is there a better to get stats from iptables, but without iptc ?
Upvotes: 0
Views: 132
Reputation: 4704
It is not guaranteed that all columns would be separated by more than one space for the iptables output. It just guarantees that there is at least one space. Following is a snippet from that command's output (when run on one of my machines), and you can see that happening:
$> iptables -nvL
...
0 0 ACCEPT all -- docker0 docker0 0.0.0.0/0 0.0.0.0/0
...
Fortunately, the values in first 9 columns will not have any spaces. So you can do the following for each line to get the data in the way you want:
fs = s.split()
if len(fs) > 9:
fs[9] = " ".join(fs[9:])
fs = fs[:10]
Upvotes: 1