"""Opening a port in whichever firewall a Linux host runs: firewalld, ufw or iptables. The firewall step of the agents a fix sets up (SNMP's udp/161, the Zabbix agent's tcp/``ListenPort``). """ from __future__ import annotations from typing import TYPE_CHECKING from napalm_device_types import FixStepOutcomeDict from napalm_linux._snmp_agent import _source, firewalld_allow_port class OpenPortMixin: """``_allow_sources``: the shared firewall step.""" def _allow_sources(self, allowed: list[str], port: int, proto: str) -> FixStepOutcomeDict: """Open *proto*/*port* for *allowed* in the host's firewall: firewalld, ufw or iptables, whichever runs; ``ok`` with nothing to do for none or no sources.""" sources = [_source(s) for s in allowed] if not sources: return {"ok": True, "output": "no sources given; firewall unchanged"} # firewalld first: its hosts have iptables too, and an iptables ACCEPT does # not lift firewalld's reject (both are nftables tables; a drop in either wins). if self._send("systemctl is-active firewalld 2>/dev/null") == "active": done = f"{proto}/{port} open in firewalld for {', '.join(sources)}" return self._root_outcome(firewalld_allow_port(sources, port, proto), 60, done) if self._send("command -v ufw 2>/dev/null"): rules = [f"ufw allow from {s} to any port {port} proto {proto}" for s in sources] elif self._send("command -v iptables 2>/dev/null"): rules = [ f"{{ iptables -C INPUT -s {s} -p {proto} --dport {port} -j ACCEPT 2>/dev/null" f" || iptables -I INPUT -s {s} -p {proto} --dport {port} -j ACCEPT; }}" for s in sources ] else: return {"ok": True, "output": "no host firewall (ufw, iptables); nothing to open"} done = f"{proto}/{port} open for {', '.join(sources)}" return self._root_outcome(" && ".join(rules), 30, done) if TYPE_CHECKING: # pragma: no cover - the driver's def _send(self, command: str, read_timeout: float = 100) -> str: ... def _root_outcome(self, command: str, timeout: float, done: str) -> FixStepOutcomeDict: ...