萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 網路安全 >  >> 資訊安全防護

Linux 防火牆 (iptables) 啟用、關閉與開放端口完整指令速查

一、服務層級控制

永久生效(跨重開機)

# 查看啟動狀態
chkconfig --list | grep iptables

# 開機自動啟用
chkconfig iptables on

# 開機不啟用
chkconfig iptables off

即時生效(重開機失效)

# 啟動
service iptables start

# 停止
service iptables stop

# 重啟
service iptables restart

# 狀態
service iptables status
提示:RHEL 7 / CentOS 7 以上預設使用 firewalld,對應指令為 systemctl start/stop/enable/disable firewalld;iptables-service 套件安裝後可續用傳統指令。

二、開放常用端口(修改 /etc/sysconfig/iptables)

# 備份原規則
cp /etc/sysconfig/iptables /etc/sysconfig/iptables.bak

# 編輯規則檔
vi /etc/sysconfig/iptables

# 在 *filter 鏈中加入(建議放在 COMMIT 之前):
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT   # SSH
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT   # HTTP
-A INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT  # HTTPS
-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT # MySQL (僅限內網)
-A INPUT -m state --state NEW -m udp -p udp --dport 1194 -j ACCEPT # OpenVPN

# 存檔後重載
service iptables restart

三、常用 iptables 直接操作指令(即時生效,不寫入配置檔)

需求指令
允許特定 IP 存取 SSHiptables -A INPUT -s 192.168.1.100 -p tcp --dport 22 -j ACCEPT
允許整個網段存取 HTTPiptables -A INPUT -s 10.0.0.0/8 -p tcp --dport 80 -j ACCEPT
封鎖特定 IP 所有連線iptables -A INPUT -s 203.0.113.50 -j DROP
刪除某條規則(按行號)iptables -D INPUT 5
查看規則含行號iptables -L -n -v --line-numbers
儲存規則至配置檔service iptables save 或 iptables-save > /etc/sysconfig/iptables

四、關鍵參數說明

  • -A:追加規則到鏈尾
  • -I:插入規則到鏈首(優先匹配)
  • -D:刪除規則
  • -p:協定 (tcp/udp/icmp/all)
  • --dport:目的埠
  • --sport:來源埠
  • -s:來源 IP/網段
  • -d:目的 IP/網段
  • -j:動作 (ACCEPT/DROP/REJECT/LOG)
  • -m state --state:連線狀態 (NEW/ESTABLISHED/RELATED/INVALID)

五、最佳實務建議

  1. 預設拒絕:iptables -P INPUT DROP,再逐項放行必要服務。
  2. 允許已建立/相關連線:iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT(放在最前)。
  3. 允許回環介面:iptables -A INPUT -i lo -j ACCEPT。
  4. 限制 ICMP:僅允許 Echo Request (Type 8)、Destination Unreachable (Type 3)、Time Exceeded (Type 11)。
  5. 定期審核:iptables -L -n -v 檢查計數器,移除零流量規則。
  6. 使用腳本管理:將規則寫入 Shell 腳本,版本控管,部署時執行腳本。

六、結語

iptables 是 Linux 核心 Netfilter 框架的使用者空間控制工具,功能強大但語法繁瑣。生產環境建議採用「配置檔 + 腳本 + 版本控制」模式,並搭配 fail2ban、psad 等主動防禦工具,構建多層次主機防護體系。

copyright © 萬盛學電腦網 all rights reserved