Python-iptables is a Python project that provides bindings to the iptables C libraries in Linux. Interoperability with iptables is achieved using the iptables C libraries (libiptc, libxtables, and iptables extensions), not calling the iptables executable and parsing its output as most other iptables wrapper libraries do; this makes python-iptables faster and not prone to parsing errors, at the same time leveraging all available iptables match and target extensions without further work. If you need further information on how iptables and netfilter work, this is a great summary.
Iptables is organized into a hierarchy: the basic building blocks are tables which contain chains, and chains consist of the actual rules that tell netfilter what to do with network packets. A rule contains at least one (possibly more) match(es) and a target. There are a few default tables and chains, but users can create further chains to organize their rules into blocks. A rule can also jump into another chain (kind of like calling a subroutine).
Tables, chains and rules (image from thegeekstuff.com)
Python-iptables makes it very easy to programatically manipulate or alter chains and rules. E.g. to traverse all rules in the INPUT chain in the FILTER table:
>>> import iptc
>>> table = iptc.TABLE_FILTER
>>> inp = iptc.Chain(table, "INPUT")
>>> for r in inp.rules:
... print r.src, "->", r.dst, "L4:", r.protocol,
... for m in r.matches:
... print "match:", m.name,
... print "target:", r.target.name
...
192.168.1.0/255.255.255.0 -> 192.168.2.0/255.255.255.0 L4: udp match: udp target: ACCEPT
192.168.1.0/255.255.255.0 -> 192.168.2.0/255.255.255.0 L4: tcp match: tcp target: ACCEPT
>>>
You are of course free to create new rules:
>>> import iptc
>>> rule = iptc.Rule()
>>> rule.dst = "192.168.100.1"
>>> rule.protocol = "tcp"
>>> rule.in_interface = "eth0"
>>> match = iptc.Match(rule, "tcp")
>>> match.dport = "8000"
>>> rule.add_match(match)
>>> target = iptc.Target(rule, "REDIRECT")
>>> rule.target = target
>>> chain = iptc.Chain(iptc.TABLE_NAT, "iptc_test_redirect")
>>> iptc.TABLE_NAT.create_chain(chain)
>>> target.reset()
>>> target.to_ports = "1234-1235"
>>> rule.target = target
>>> chain.insert_rule(rule)
>>> for r in chain.rules:
... print r.src, "->", r.dst, "L4:", r.protocol,
... for m in r.matches:
... print "match:", m.name,
... print "target:", r.target.name
...
0.0.0.0/0.0.0.0 -> 192.168.100.1/255.255.255.255 L4: tcp match: tcp target: REDIRECT
>>> chain.delete_rule(rule)
>>> chain.flush()
>>> chain.delete()
>>>
This is equivalent to the following command line sequence:
# iptables -t nat -N iptc_test_redirect
# iptables -t nat -A iptc_test_redirect -d 192.168.100.1 -i eth0 -p tcp --dport 8000 -j REDIRECT --to-ports 1234-1235
# iptables -t nat -F iptc_test_redirect
# iptables -t nat -X iptc_test_redirect
You can find detailed API documentation and further examples here. The source code is available on Github.