Configuring a good firewall is a basic task when securing modern operating systems. Iptables is the standard included in most Linux distributions, at least until nftables replaces it. In this article, we will learn how to configure iptables rules using a Python script.
We install the necessary Python module using pip:
pip install python-iptables --user
In this example, we will program a basic script where we block an IP address A.B.C.D and verify that the rule has been inserted:
vi iptest.py
import iptc
rule = iptc.Rule()
rule.src = "A.B.C.D"
rule.create_target("DROP")
rule.target = iptc.Target(rule, "DROP")
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
chain.insert_rule(rule)
rawdata = iptc.easy.dump_table('filter', ipv6=False)
for rule in rawdata['INPUT']:
print rule
if 'src' in rule and 'target' in rule:
if rule['src'] == 'A.B.C.D/32' and rule['target'] == 'DROP':
print 'Matched rule'