Python bindings for iptables providing programmatic control over Linux netfilter rules
—
Core functionality for managing iptables tables and chains in IPv4 networks. This module provides the foundation for all iptables operations, including table access, chain creation and management, and policy configuration.
Tables are the top-level containers in iptables that organize chains by their primary function. Each table serves a specific purpose in the packet processing pipeline.
class Table:
"""
Represents an iptables table (filter, nat, mangle, raw, security).
Class Constants:
- FILTER: "filter" - Default table for filtering packets
- NAT: "nat" - Network Address Translation table
- MANGLE: "mangle" - Packet alteration table
- RAW: "raw" - Raw packet processing table
- SECURITY: "security" - SELinux security table
- ALL: List of all available table names
"""
FILTER: str
NAT: str
MANGLE: str
RAW: str
SECURITY: str
ALL: list
def __init__(self, name: str, autocommit: bool = None):
"""
Initialize a Table object.
Args:
name: Table name (use Table constants)
autocommit: Enable automatic commits (default: True)
"""
@property
def autocommit(self) -> bool:
"""Whether operations are automatically committed"""
@autocommit.setter
def autocommit(self, value: bool) -> None:
"""Set autocommit behavior"""
@property
def chains(self) -> list:
"""List of Chain objects in this table"""
def commit(self) -> None:
"""Commit pending operations to kernel"""
def refresh(self) -> None:
"""Refresh table state from kernel"""
def close(self) -> None:
"""Close connection handle"""
def create_chain(self, chain: str) -> 'Chain':
"""
Create a new chain in this table.
Args:
chain: Chain name
Returns:
Chain object for the new chain
"""
def delete_chain(self, chain: str) -> None:
"""
Delete a chain from this table.
Args:
chain: Chain name or Chain object
"""
def flush_entries(self, chain: str) -> None:
"""
Remove all rules from a chain.
Args:
chain: Chain name
"""
def is_chain(self, chain: str) -> bool:
"""
Check if chain exists in this table.
Args:
chain: Chain name
Returns:
True if chain exists
"""
def builtin_chain(self, chain: str) -> bool:
"""
Check if chain is a built-in chain.
Args:
chain: Chain name
Returns:
True if chain is built-in
"""
def zero_entries(self, chain: str) -> None:
"""
Zero all packet and byte counters in a chain.
Args:
chain: Chain name
"""
def rename_chain(self, old_name: str, new_name: str) -> None:
"""
Rename a chain in this table.
Args:
old_name: Current chain name
new_name: New chain name
"""Chains are containers for rules within a table. They define the order in which rules are processed and can have default policies for unmatched packets.
class Chain:
"""
Represents a chain within an iptables table.
"""
def __init__(self, table: Table, name: str):
"""
Initialize a Chain object.
Args:
table: Parent Table object
name: Chain name
"""
@property
def name(self) -> str:
"""Chain name"""
@property
def table(self) -> Table:
"""Parent Table object"""
@property
def rules(self) -> list:
"""List of Rule objects in this chain"""
def append_rule(self, rule: 'Rule') -> None:
"""
Add rule to end of chain.
Args:
rule: Rule object to add
"""
def insert_rule(self, rule: 'Rule', position: int = 0) -> None:
"""
Insert rule at specific position.
Args:
rule: Rule object to insert
position: Position to insert at (0 = beginning)
"""
def delete_rule(self, rule: 'Rule') -> None:
"""
Remove rule from chain.
Args:
rule: Rule object to remove
"""
def flush(self) -> None:
"""Remove all rules from chain"""
def set_policy(self, policy: str, counters: tuple = None) -> None:
"""
Set default policy for chain.
Args:
policy: Policy name (ACCEPT, DROP, QUEUE, RETURN)
counters: Optional (packets, bytes) counters
"""
def get_policy(self) -> tuple:
"""
Get current policy and counters.
Returns:
Tuple of (policy_name, (packets, bytes))
"""
def is_builtin(self) -> bool:
"""
Check if this is a built-in chain.
Returns:
True if built-in chain
"""
def get_counters(self) -> tuple:
"""
Get packet and byte counters for this chain.
Returns:
Tuple of (packets, bytes)
"""
def zero_counters(self) -> None:
"""Zero packet and byte counters for this chain"""
def rename(self, new_name: str) -> None:
"""
Rename this chain.
Args:
new_name: New chain name
"""Function to check which tables are available in the current kernel configuration.
def is_table_available(name: str) -> bool:
"""
Check if specified table is available in kernel.
Args:
name: Table name to check
Returns:
True if table is available
"""import iptc
# Access the filter table
table = iptc.Table(iptc.Table.FILTER)
# Check if table is available first
if iptc.is_table_available("mangle"):
mangle_table = iptc.Table(iptc.Table.MANGLE)
# Disable autocommit for batch operations
table.autocommit = False
# ... perform multiple operations ...
table.commit()
table.autocommit = Trueimport iptc
table = iptc.Table(iptc.Table.FILTER)
# Create a custom chain
custom_chain = table.create_chain("my_custom_chain")
# Access built-in chains
input_chain = iptc.Chain(table, "INPUT")
output_chain = iptc.Chain(table, "OUTPUT")
# Set chain policy
input_chain.set_policy(iptc.Policy.DROP)
# Check policy
policy, counters = input_chain.get_policy()
print(f"Policy: {policy}, Packets: {counters[0]}, Bytes: {counters[1]}")
# List all chains in table
for chain in table.chains:
print(f"Chain: {chain.name}, Builtin: {chain.is_builtin()}")
# Flush chain (remove all rules)
custom_chain.flush()
# Delete custom chain
table.delete_chain("my_custom_chain")import iptc
try:
# Try to access a table that might not exist
table = iptc.Table("nonexistent")
except iptc.IPTCError as e:
print(f"Table access failed: {e}")
try:
table = iptc.Table(iptc.Table.FILTER)
# Try to create a chain that already exists
table.create_chain("INPUT") # INPUT is built-in
except iptc.IPTCError as e:
print(f"Chain creation failed: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-python-iptables