Linux iptables:端口重定向示例

时间:2020-01-09 10:41:51  来源:igfitidea点击:

如何使用iptables将80端口重定向到8123?
通过将规则插入到nat表的PREROUTING链中,您可以轻松地重定向传入流量。
您可以使用REDIRECT目标设置目标端口。

语法

语法如下,将tcp $srcPortNumber端口重定向到$dstPortNumber:

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport $srcPortNumber -j REDIRECT --to-port $dstPortNumber

语法如下,将udp $srcPortNumber端口重定向到$dstPortNumber:

iptables -t nat -A PREROUTING -i eth0 -p udp --dport $srcPortNumber -j REDIRECT --to-port $dstPortNumber

用您的实际接口名称替换eth0。
源和目标ip的以下语法匹配:

iptables -t nat -I PREROUTING --src $SRC_IP_MASK --dst $DST_IP -p tcp --dport $portNumber -j REDIRECT --to-ports $rediectPort

例子:

以下示例将TCP端口25重定向到端口2525:

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 25 -j REDIRECT --to-port 2525

在此示例中,端口80上的所有传入流量都重定向到端口8123

iptables -t nat -I PREROUTING --src 0/0 --dst 192.168.1.5 -p tcp --dport 80 -j REDIRECT --to-ports 8123

引用iptables手册页:

This  target is only valid in the nat table, in the PREROUTING and OUTPUT 
       chains, and user-defined chains which are only  called  from  those
       chains.   It redirects the packet to the machine itself by changing the
       destination IP  to  the  primary  address  of  the  incoming  interface
       (locally-generated  packets  are  mapped to the 127.0.0.1 address).  It
       takes one option:

       --to-ports port[-port]
              This specifies a destination port or  range  of  ports  to  use:
              without  this,  the  destination port is never altered.  This is
              only valid if the rule also specifies -p tcp or -p udp.

OUTPUT链示例:

iptables -t nat -I OUTPUT --src 0/0 --dst 192.168.1.5 -p tcp --dport 80 -j REDIRECT --to-ports 8123

如何查看NAT规则?

输入以下命令:

iptables -t nat -L -n -v

如何保存NAT重定向规则?

输入以下命令:

iptables-save