python-iptables

raw JSON →
1.2.0 verified Mon Apr 27 auth: no python maintenance

Python bindings for iptables, providing a Pythonic interface to manipulate Linux netfilter rules. Currently at v1.2.0, with infrequent releases and limited maintenance.

pip install python-iptables
error PermissionError: [Errno 1] Operation not permitted
cause Script not run as root; iptables requires root privileges.
fix
Run with sudo: sudo python script.py
error AttributeError: module 'iptc' has no attribute 'Table'
cause Wrong import; the correct module is iptc, not iptables.
fix
Use 'from iptc import Table' instead of 'import iptables'.
error AttributeError: 'NoneType' object has no attribute 'append'
cause Chain object is None because chain name does not exist or table was not flushed properly.
fix
Ensure chain exists (e.g., from table.chains) or create chain first.
breaking Must be run as root (or with CAP_NET_ADMIN). Non-root users will get permissions error.
fix Run script with sudo or set capabilities on Python interpreter.
deprecated No longer maintained; last release 1.2.0 (2020). Consider alternatives like nftables for new projects.
fix Use python-nftables or subprocess calls to iptables-legacy.
gotcha Table.commit() must be called to apply rule changes. Forgetting it leaves rules unapplied.
fix After modifying rules/flushing chain, call table.commit().

List all rules in the FILTER table. Run as root.

import os
from iptc import Table, Chain, Rule, Match, Target

table = Table(Table.FILTER)
for chain in table.chains:
    print(f"Chain {chain.name}")
    for rule in chain.rules:
        print(f"  Rule: {rule.src} -> {rule.dst}")