使用iptables端口转发多个端口

我有端口30000-32000上的VPS A(1.1.1.1)上运行的服务。

我想让VPS B(2.2.2.2)将他们转移到20000-22000。

(你可以看看下面的演示图链接,了解我想实现的目标:D)

转发到不同的端口

我使用下面的命令设置iptables

iptables -t nat -A PREROUTING -p tcp --dport 20000:22000 -j DNAT --to-destination 1.1.1.1:30000-32000 iptables -t nat -A POSTROUTING -p tcp -d 1.1.1.1 --dport 30000:32000 -j SNAT --to-source 2.2.2.2 20000:22000 iptables -t nat -A PREROUTING -p udp --dport 20000:22000 -j DNAT --to-destination 1.1.1.1:30000-32000 iptables -t nat -A POSTROUTING -p udp -d 1.1.1.1 --dport 30000:32000 -j SNAT --to-source 2.2.2.2 20000:22000 

经过一些testing,我发现似乎只有20000端口是转发原始服务器的端口30000.但是,其他端口不工作。

我检查了以下4件事情:1. VPS A(1.1.1.1)的服务在端口30000 – 32000上运行的服务function齐全

  1. VPS B端口转发设置检查VPS B上的sysctl时,启用了ipv4转发。

(即net.ipv4.ip_forward = 1

  1. VPS B的iptable设置。 我看起来很好。 您可以点击下面的链接进行确切的设置。

iptables设置

  1. 我也尝试从VPS A到VPS B(即VPS A(30000-32000)>> VPS B(30000-32000))进行正常的多端口转发。

(你可以看看下面的演示图链接,我想达到什么:D)

一切工作正常。

我真的不知道如何实现它。 任何帮助表示赞赏! 先谢谢你!

您需要更改iptables规则。 您的DNAT规则不会过滤来自用户的传入stream量的目标IP地址。 您的SNAT规则不会过滤来自A服务器的传入stream量的源IP地址和源端口30000:32000范围。 您需要在B服务器上:

 iptables -t nat -A PREROUTING -p tcp -d 2.2.2.2 --dport 20000:22000 -j DNAT --to-destination 1.1.1.1:30000-32000 iptables -t nat -A POSTROUTING -p tcp -s 1.1.1.1 --sport 30000:32000 -j SNAT --to-source 2.2.2.2:20000:22000 iptables -t nat -A PREROUTING -p udp -d 2.2.2.2 --dport 20000:22000 -j DNAT --to-destination 1.1.1.1:30000-32000 iptables -t nat -A POSTROUTING -p udp -s 1.1.1.1 --sport 30000:32000 -j SNAT --to-source 2.2.2.2:20000:22000