Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 防火牆啟用與連接埠管理速查:iptables / firewalld / ufw 三大工具對照

編輯:Linux 教學

Linux 防火牆管理經歷 iptables → firewalld → ufw 三代演進。本文提供針對不同發行版的 啟用/停用/狀態查詢/開放埠口/持久化 統一速查表,並說明底層關係。

工具選擇指南

工具適用發行版層級特色
iptables所有 Linux (核心模組)底層規則直接寫入 netfilter、腳本自動化首選、無管理服務
firewalldRHEL/CentOS/Fedora 7+、openSUSE中層 (D-Bus 服務)動態區域、運行時/永久配置分離、支援 NetworkManager 整合
ufwUbuntu/Debian、衍生版高層 (Python 腳本)簡單語法、預設拒絕進站、適合桌面/簡單伺服器

關鍵點:三者底層皆操作 netfilter,同時只能啟用一種管理介面,混用會導致規則衝突。

核心操作對照表

操作iptables (服務名: iptables)firewalld (服務名: firewalld)ufw
啟用並開機自啟systemctl enable --now iptablessystemctl enable --now firewalldufw enable
停用並關閉自啟systemctl disable --now iptablessystemctl disable --now firewalldufw disable
僅啟用 (不持久)systemctl start iptablessystemctl start firewalldufw enable (即持久)
僅停用 (不持久)systemctl stop iptablessystemctl stop firewalldufw disable
查看狀態systemctl status iptables
iptables -nvL --line-numbers
firewall-cmd --state
firewall-cmd --list-all
ufw status verbose
開放單一埠口 (TCP)iptables -A INPUT -p tcp --dport 80 -j ACCEPT
service iptables save
firewall-cmd --add-port=80/tcp --permanent
firewall-cmd --reload
ufw allow 80/tcp
開放埠口範圍iptables -A INPUT -p tcp --dport 3000:3100 -j ACCEPTfirewall-cmd --add-port=3000-3100/tcp --permanentufw allow 3000:3100/tcp
開放特定 IP 存取埠口iptables -A INPUT -s 192.168.1.100 -p tcp --dport 22 -j ACCEPTfirewall-cmd --add-rich-rule='rule family=ipv4 source address=192.168.1.100 port port=22 protocol=tcp accept' --permanentufw allow from 192.168.1.100 to any port 22
移除規則iptables -D INPUT -p tcp --dport 80 -j ACCEPTfirewall-cmd --remove-port=80/tcp --permanentufw delete allow 80/tcp
查看規則編號iptables -nL --line-numbersfirewall-cmd --list-allufw status numbered
儲存/持久化iptables-save > /etc/sysconfig/iptables
或 service iptables save
自動 (--permanent 寫入 /etc/firewalld/)自動 (寫入 /etc/ufw/)

firewalld 區域概念速記

  • public (預設):不可信網路,僅開放必要服務
  • internal:信任內網,開放更多服務
  • trusted:完全信任,接受所有連線
  • dmz:非軍事區,僅開放特定對外服務
  • work/home:對應網路類型
  • 指定區域:--zone=public (預設可省略)

iptables 直接操作範例腳本 (適用所有發行版)

#!/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。核心原則:預設拒絕進站、最小授權原則、運行時驗證後再持久化、單一管理介面。

Copyright © Windows教程網 All Rights Reserved