萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 防火牆 iptables 端口管理與佔用排查實戰速查表

iptables 端口開放/關閉基本語法

# 開放單一 TCP 埠
iptables -A INPUT -p tcp --dport 111 -j ACCEPT

# 關閉單一 TCP 埠
iptables -A INPUT -p tcp --dport 111 -j DROP

# 開放多個不連續埠 (multiport)
iptables -A INPUT -p tcp -m multiport --dports 21,20,22 -j ACCEPT

# 開放連續埠範圍
iptables -A INPUT -p udp --dport 8001:8140 -j ACCEPT

# 預設拒絕其餘 TCP 連線 (放在規則最後)
iptables -A INPUT -p tcp -j REJECT --reject-with tcp-reset

持久化規則

# CentOS/RHEL 6/7
service iptables save
# 或直接編輯
vi /etc/sysconfig/iptables

# Debian/Ubuntu (使用 iptables-persistent)
apt-get install iptables-persistent
netfilter-persistent save

重新載入生效

service iptables restart
# 或
systemctl restart iptables

端口佔用排查三步驟

  1. 查看埠監聽狀態
    netstat -tlnp | grep :8083
    ss -tlnp | grep :8083  # 現代替代指令
  2. 定位佔用進程
    lsof -i :8083
    # COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
    # java    1234 root   45u  IPv6  12345      0t0  TCP *:8083 (LISTEN)
  3. 終止進程釋放埠
    kill -9 1234
    # 驗證
    ss -tlnp | grep :8083 || echo "Port released"

進階技巧

  • 只允許特定 IP 存取埠:
    iptables -A INPUT -p tcp -s 192.168.1.100 --dport 3306 -j ACCEPT
    iptables -A INPUT -p tcp --dport 3306 -j DROP
  • 查看完整規則鏈:
    iptables -nvL --line-numbers
  • 刪除特定規則:
    iptables -D INPUT 5  # 刪除 INPUT 鏈第 5 條規則

systemd 時代替代方案

RHEL 8+/CentOS 8+/Ubuntu 20.04+ 建議改用 firewalld 或 nftables:

# firewalld 開放埠
firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --reload

# nftables 範例
nft add rule inet filter input tcp dport 8080 accept
copyright © 萬盛學電腦網 all rights reserved