Linux 防火牆管理經歷 iptables → firewalld → ufw 三代演進。本文提供針對不同發行版的 啟用/停用/狀態查詢/開放埠口/持久化 統一速查表,並說明底層關係。
| 工具 | 適用發行版 | 層級 | 特色 |
|---|---|---|---|
| iptables | 所有 Linux (核心模組) | 底層 | 規則直接寫入 netfilter、腳本自動化首選、無管理服務 |
| firewalld | RHEL/CentOS/Fedora 7+、openSUSE | 中層 (D-Bus 服務) | 動態區域、運行時/永久配置分離、支援 NetworkManager 整合 |
| ufw | Ubuntu/Debian、衍生版 | 高層 (Python 腳本) | 簡單語法、預設拒絕進站、適合桌面/簡單伺服器 |
關鍵點:三者底層皆操作 netfilter,同時只能啟用一種管理介面,混用會導致規則衝突。
| 操作 | iptables (服務名: iptables) | firewalld (服務名: firewalld) | ufw |
|---|---|---|---|
| 啟用並開機自啟 | systemctl enable --now iptables | systemctl enable --now firewalld | ufw enable |
| 停用並關閉自啟 | systemctl disable --now iptables | systemctl disable --now firewalld | ufw disable |
| 僅啟用 (不持久) | systemctl start iptables | systemctl start firewalld | ufw enable (即持久) |
| 僅停用 (不持久) | systemctl stop iptables | systemctl stop firewalld | ufw disable |
| 查看狀態 | systemctl status iptablesiptables -nvL --line-numbers | firewall-cmd --statefirewall-cmd --list-all | ufw status verbose |
| 開放單一埠口 (TCP) | iptables -A INPUT -p tcp --dport 80 -j ACCEPTservice iptables save | firewall-cmd --add-port=80/tcp --permanentfirewall-cmd --reload | ufw allow 80/tcp |
| 開放埠口範圍 | iptables -A INPUT -p tcp --dport 3000:3100 -j ACCEPT | firewall-cmd --add-port=3000-3100/tcp --permanent | ufw allow 3000:3100/tcp |
| 開放特定 IP 存取埠口 | iptables -A INPUT -s 192.168.1.100 -p tcp --dport 22 -j ACCEPT | firewall-cmd --add-rich-rule='rule family=ipv4 source address=192.168.1.100 port port=22 protocol=tcp accept' --permanent | ufw allow from 192.168.1.100 to any port 22 |
| 移除規則 | iptables -D INPUT -p tcp --dport 80 -j ACCEPT | firewall-cmd --remove-port=80/tcp --permanent | ufw delete allow 80/tcp |
| 查看規則編號 | iptables -nL --line-numbers | firewall-cmd --list-all | ufw status numbered |
| 儲存/持久化 | iptables-save > /etc/sysconfig/iptables或 service iptables save | 自動 (--permanent 寫入 /etc/firewalld/) | 自動 (寫入 /etc/ufw/) |
public (預設):不可信網路,僅開放必要服務internal:信任內網,開放更多服務trusted:完全信任,接受所有連線dmz:非軍事區,僅開放特定對外服務work/home:對應網路類型--zone=public (預設可省略)#!/bin/bash
IPT=/sbin/iptables
$IPT -F; $IPT -X; $IPT -Z
$IPT -P INPUT DROP; $IPT -P FORWARD DROP; $IPT -P OUTPUT ACCEPT
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
$IPT -A INPUT -p icmp -j ACCEPT
$IPT -A INPUT -p tcp --dport 22 -j ACCEPT
$IPT -A INPUT -p tcp --dport 80,443 -j ACCEPT
iptables-save > /etc/sysconfig/iptables
| 現象 | 原因/解決 |
|---|---|
| 規則生效後 SSH 斷線 | 未先放行 22 埠 → 掛載救援模式或 VNC 主控台修正 |
| firewalld 與 iptables 服務衝突 | systemctl disable --now iptables 再啟用 firewalld |
| Docker 容器網路不通 | Docker 操作 iptables NAT 鏈,需配置 firewalld --zone=trusted --add-interface=docker0 |
| 重啟後規則消失 | iptables 未 save、firewalld 未加 --permanent、ufw 未 enable |
現代 Linux 防火牆選型:RHEL 系用 firewalld、Ubuntu 系用 ufw、腳本/容器/嵌入式直接用 iptables。核心原則:預設拒絕進站、最小授權原則、運行時驗證後再持久化、單一管理介面。