將訪問本機 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
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
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 — 客戶端測試連通性rp_filter 設置寬鬆 (net.ipv4.conf.all.rp_filter=2)。iptables 實為 iptables-nft 兼容層,規則語法不變但底層不同。