欢迎各位兄弟 发布技术文章
这里的技术是共享的
python 来判断 防火墙 是否启用
DOS 命令是: # netsh advfirewall show allprofiles state
在 Python 中,可以通过检查操作系统防火墙的状态来判断它是否启用。不同的操作系统(Windows、Linux、macOS)有不同的方法。以下是几种常见的方法:
在 Windows 上,可以使用 subprocess
调用 netsh
命令来检查防火墙状态:
pythonimport subprocess def is_windows_firewall_enabled(): try: # 获取防火墙状态 result = subprocess.run( ["netsh", "advfirewall", "show", "allprofiles", "state"], capture_output=True, text=True, check=True ) # 检查输出中是否包含 "ON"(启用) return "ON" in result.stdout except subprocess.CalledProcessError: return False if is_windows_firewall_enabled(): print("Windows 防火墙已启用") else: print("Windows 防火墙未启用")
netsh advfirewall show allprofiles state
返回域、专用、公用三个防火墙配置文件的状态。
如果任何一个配置文件的状态是 ON
,则防火墙被视为启用。
在 Linux 上,常见的防火墙管理工具有 iptables
、ufw
、nftables
等。以下是检查 ufw
状态的示例:
ufw
(Ubuntu)pythonimport subprocess def is_linux_ufw_enabled(): try: result = subprocess.run( ["sudo", "ufw", "status"], # 需要 sudo 权限 capture_output=True, text=True, check=True ) return "Status: active" in result.stdout except subprocess.CalledProcessError: return False if is_linux_ufw_enabled(): print("Linux UFW 防火墙已启用") else: print("Linux UFW 防火墙未启用")
firewalld
(CentOS/RHEL)pythonimport subprocess def is_linux_firewalld_enabled(): try: result = subprocess.run( ["sudo", "firewall-cmd", "--state"], # 需要 sudo 权限 capture_output=True, text=True, check=True ) return "running" in result.stdout except subprocess.CalledProcessError: return False if is_linux_firewalld_enabled(): print("Linux firewalld 防火墙已启用") else: print("Linux firewalld 防火墙未启用")
在 macOS 上,可以使用 defaults
或 pfctl
检查防火墙状态:
pythonimport subprocess def is_macos_firewall_enabled(): try: result = subprocess.run( ["defaults", "read", "/Library/Preferences/com.apple.alf", "globalstate"], capture_output=True, text=True, check=True ) # 0=关闭,1=专用,2=公用,3=完全启用 return result.stdout.strip() != "0" except subprocess.CalledProcessError: return False if is_macos_firewall_enabled(): print("macOS 防火墙已启用") else: print("macOS 防火墙未启用")
如果你希望代码能在不同操作系统上运行,可以结合 platform
模块:
pythonimport platform import subprocess def is_firewall_enabled(): os_name = platform.system() if os_name == "Windows": return is_windows_firewall_enabled() elif os_name == "Linux": return is_linux_ufw_enabled() # 或 firewalld elif os_name == "Darwin": # macOS return is_macos_firewall_enabled() else: print("未知操作系统") return False if is_firewall_enabled(): print("防火墙已启用") else: print("防火墙未启用")
权限问题:Linux 和 macOS 的某些命令需要 sudo
权限。
不同防火墙工具:Linux 上可能有 iptables
、ufw
、firewalld
等不同防火墙程序,需针对检查。
更精确的检测:可以结合 psutil
或系统 API 来检查防火墙进程是否运行。
如果你的应用需要在企业环境中检测防火墙状态,建议结合 WMI (Windows) 或 D-Bus (Linux) 等更底层的方法。