""" Command-builder module for managing nftables on a Linux VPS. Each function returns a bash command string ready for execution. """ def status_cmd() -> str: """Check if nft is installed, its version, and the systemctl status of nftables.""" return ( "which nft && nft --version; " "systemctl status nftables --no-pager" ) def install_cmd() -> str: """Install nftables and enable the service.""" return ( "apt-get update && apt-get install -y nftables && " "systemctl enable nftables && systemctl start nftables" ) def list_cmd() -> str: """List the full nftables ruleset.""" return "nft list ruleset" def list_tables_cmd() -> str: """List all nftables tables.""" return "nft list tables" def list_chains_cmd(table: str = "inet filter") -> str: """List all chains in the given table.""" return f"nft list chains {table}" def add_rule_cmd(table: str, chain: str, rule: str) -> str: """Add a rule to a chain in a table. Example: add_rule_cmd("inet filter", "input", "tcp dport 80 accept") """ return f"nft add rule {table} {chain} {rule}" def delete_rule_cmd(table: str, chain: str, handle: int) -> str: """Delete a rule by handle number.""" return f"nft delete rule {table} {chain} handle {handle}" def flush_cmd(table: str | None = None, chain: str | None = None) -> str: """Flush rules. Optionally scope to a table or table+chain.""" if table and chain: return f"nft flush chain {table} {chain}" if table: return f"nft flush table {table}" return "nft flush ruleset" def create_table_cmd(family: str, name: str) -> str: """Create a new table (e.g. family='inet', name='filter').""" return f"nft add table {family} {name}" def delete_table_cmd(family: str, name: str) -> str: """Delete a table.""" return f"nft delete table {family} {name}" def create_chain_cmd( table: str, chain: str, chain_type: str = "filter", hook: str = "input", priority: int = 0, ) -> str: """Create a base chain with type, hook, and priority.""" return ( f"nft add chain {table} {chain} " f"'{{ type {chain_type} hook {hook} priority {priority}; }}'" ) def save_cmd() -> str: """Save the current ruleset to /etc/nftables.conf.""" return "nft list ruleset > /etc/nftables.conf" def restore_cmd() -> str: """Restore rules from /etc/nftables.conf.""" return "nft -f /etc/nftables.conf" def counters_cmd() -> str: """List all nftables counters.""" return "nft list counters" def config_cmd() -> str: """Display the saved nftables configuration file.""" return "cat /etc/nftables.conf" def uninstall_cmd() -> str: """Stop, disable, and remove nftables.""" return ( "systemctl stop nftables; systemctl disable nftables; " "apt-get purge -y nftables && apt-get autoremove -y" )