如何用Python命令或模块检查Windows防火墙状态?支持Linux吗?
Hey Quang, great question! Let’s walk through how to check firewall status on both Windows and Linux using Python, plus a cross-platform approach to cover both systems.
On Windows, the easiest way is to leverage the built-in netsh command via Python’s subprocess module. This avoids needing extra third-party libraries and works across all modern Windows versions:
import subprocess def check_windows_firewall(): try: # Fetch status for all firewall profiles (domain, private, public) result = subprocess.run( ["netsh", "advfirewall", "show", "allprofiles"], capture_output=True, text=True, check=True ) # Parse and print the state of each profile for line in result.stdout.splitlines(): if "State" in line: profile_name, status = line.split(":", 1) print(f"{profile_name.strip()}: {status.strip()}") except subprocess.CalledProcessError as e: print(f"Failed to check firewall: {e.stderr.strip()}") # Run the check check_windows_firewall()
If you prefer using native Windows APIs instead of shell commands, you can use the pywin32 library (install with pip install pywin32), but this is more complex and Windows-only. The netsh method is generally simpler and more reliable for most use cases.
Linux has a few common firewall tools, so we’ll cover the two most popular ones: ufw (Ubuntu/Debian) and firewalld (RHEL/CentOS/Fedora). Again, we’ll use subprocess to call system commands.
For UFW (Ubuntu/Debian-based systems)
import subprocess def check_linux_ufw(): try: result = subprocess.run( ["ufw", "status"], capture_output=True, text=True, check=True ) print("UFW Firewall Status:\n", result.stdout) except subprocess.CalledProcessError as e: print(f"UFW Error: {e.stderr.strip()}") except FileNotFoundError: print("UFW is not installed on this system.") check_linux_ufw()
For Firewalld (RHEL/CentOS/Fedora-based systems)
import subprocess def check_linux_firewalld(): try: # First check if firewalld is running state = subprocess.run( ["firewall-cmd", "--state"], capture_output=True, text=True, check=True ).stdout.strip() print(f"Firewalld State: {state}") # Get full firewall configuration details full_config = subprocess.run( ["firewall-cmd", "--list-all"], capture_output=True, text=True, check=True ).stdout print("\nFull Firewalld Configuration:\n", full_config) except subprocess.CalledProcessError as e: print(f"Firewalld Error: {e.stderr.strip()}") except FileNotFoundError: print("Firewalld is not installed on this system.") check_linux_firewalld()
Since there’s no single Python module that supports firewalls across all operating systems, you can build a wrapper function that detects the OS and runs the appropriate check:
import subprocess import platform def check_windows_firewall(): try: result = subprocess.run( ["netsh", "advfirewall", "show", "allprofiles"], capture_output=True, text=True, check=True ) for line in result.stdout.splitlines(): if "State" in line: profile_name, status = line.split(":", 1) print(f"{profile_name.strip()}: {status.strip()}") except subprocess.CalledProcessError as e: print(f"Windows Firewall Check Error: {e.stderr.strip()}") def check_linux_ufw(): try: result = subprocess.run( ["ufw", "status"], capture_output=True, text=True, check=True ) print("UFW Firewall Status:\n", result.stdout) return True except (subprocess.CalledProcessError, FileNotFoundError): return False def check_linux_firewalld(): try: state = subprocess.run( ["firewall-cmd", "--state"], capture_output=True, text=True, check=True ).stdout.strip() print(f"Firewalld State: {state}") full_config = subprocess.run( ["firewall-cmd", "--list-all"], capture_output=True, text=True, check=True ).stdout print("\nFull Firewalld Configuration:\n", full_config) return True except (subprocess.CalledProcessError, FileNotFoundError): return False def check_firewall_status(): os_name = platform.system() if os_name == "Windows": print("Checking Windows Firewall...\n") check_windows_firewall() elif os_name == "Linux": print("Checking Linux Firewall...\n") # Try UFW first, then Firewalld if not check_linux_ufw(): if not check_linux_firewalld(): print("No supported firewall tool found. Consider checking iptables manually.") else: print(f"Unsupported operating system: {os_name}") # Run the cross-platform check check_firewall_status()
This script will automatically detect whether it’s running on Windows or Linux and execute the correct firewall check.
内容的提问来源于stack exchange,提问作者Park Yo Jin

