首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

CentOS 7/8 使用 iptables 實現端口轉發完整配置指南

     編輯:Oracle 資料庫相關知識

場景示例

將訪問本機 IP 61.144.14.72:3389 的流量轉發至後端服務器 116.6.73.229:3389 (典型 RDP 代理場景)。

前置條件

# 1. 開啟內核轉發
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
sysctl -p

# 2. 停用 firewalld (若運行),改用 iptables-service
systemctl stop firewalld
systemctl disable firewalld
yum install -y iptables-services
systemctl enable iptables
systemctl start iptables

核心轉發規則

# DNAT: 目標地址轉換 (入站)
iptables -t nat -A PREROUTING -d 61.144.14.72 -p tcp --dport 3389 -j DNAT --to-destination 116.6.73.229:3389

# SNAT: 源地址轉換 (出站,確保回包經由本機)
iptables -t nat -A POSTROUTING -d 116.6.73.229 -p tcp --dport 3389 -j SNAT --to-source 61.144.14.72

# 保存規則
service iptables save   # 寫入 /etc/sysconfig/iptables

多協議/多端口擴展範例

# TCP 9304
iptables -t nat -A PREROUTING -d 61.144.14.87 -p tcp --dport 9304 -j DNAT --to-destination 10.94.143.204:9304
iptables -t nat -A POSTROUTING -d 10.94.143.204 -p tcp --dport 9304 -j SNAT --to-source 61.144.14.87

# UDP 9305
iptables -t nat -A PREROUTING -d 61.144.14.87 -p udp --dport 9305 -j DNAT --to-destination 10.94.143.204:9305
iptables -t nat -A POSTROUTING -d 10.94.143.204 -p udp --dport 9305 -j SNAT --to-source 61.144.14.87

開機自啟動方案

方案 A:systemd 服務 (推薦)

cat > /etc/systemd/system/iptables-port-forward.service <<'EOF'
[Unit]
Description=Custom iptables Port Forward Rules
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/iptables-forward.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF

cat > /usr/local/sbin/iptables-forward.sh <<'EOF'
#!/bin/bash
iptables -t nat -F
iptables -t nat -A PREROUTING -d 61.144.14.72 -p tcp --dport 3389 -j DNAT --to-destination 116.6.73.229:3389
iptables -t nat -A POSTROUTING -d 116.6.73.229 -p tcp --dport 3389 -j SNAT --to-source 61.144.14.72
# 追加其他規則...
EOF
chmod +x /usr/local/sbin/iptables-forward.sh
systemctl enable iptables-port-forward
systemctl start iptables-port-forward

方案 B:/etc/rc.local (兼容舊版)

chmod +x /etc/rc.d/rc.local
cat >> /etc/rc.d/rc.local <<'EOF'
/usr/local/sbin/iptables-forward.sh
EOF

驗證與排錯

  • iptables -t nat -L -n -v --line-numbers — 查看計數器增長確認流量命中
  • tcpdump -i any -nn port 3389 — 抓包驗證雙向流經本機
  • nc -zv 61.144.14.72 3389 — 客戶端測試連通性
  • 檢查後端服務器防火牆是否放行源 IP (61.144.14.72) 的入站流量

避坑提示

  1. SNAT 規則不可省略,否則後端回包直接發給客戶端導致三次握手失敗 (非對稱路由)。
  2. 若本機有多張網卡,確保 rp_filter 設置寬鬆 (net.ipv4.conf.all.rp_filter=2)。
  3. CentOS 8+ 默認使用 nftables,iptables 實為 iptables-nft 兼容層,規則語法不變但底層不同。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved