在工作中经常会遇到vpc网络,内网所有机器通过唯一一台对外的proxy机器进行共享上网,这里记录一下如何做好端口转发和管理。

  1. 展示所有nat表规则 以编号标注
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
root@jumper:~# iptables -L -t nat --line-number
Chain PREROUTING (policy ACCEPT)
num target prot opt source destination
1 DNAT tcp -- anywhere anywhere tcp dpt:EtherNet/IP-1 to:192.168.1.3:2538
2 DNAT tcp -- anywhere anywhere tcp dpt:ssh to:192.168.1.2:2538
3 DNAT tcp -- anywhere anywhere tcp dpt:7687 to:192.168.1.3:7687
4 DNAT tcp -- anywhere anywhere tcp dpt:dxspider to:192.168.1.3:8873

Chain INPUT (policy ACCEPT)
num target prot opt source destination

Chain OUTPUT (policy ACCEPT)
num target prot opt source destination

Chain POSTROUTING (policy ACCEPT)
num target prot opt source destination
1 SNAT tcp -- anywhere newdev.my-domain.com tcp dpt:EtherNet/IP-1 to:192.168.1.1
2 SNAT tcp -- anywhere dev.my-domain.com tcp dpt:vnwk-prapi to:192.168.1.1
3 SNAT tcp -- anywhere dev.my-domain.com tcp dpt:ssh to:192.168.1.1
4 SNAT tcp -- anywhere newdev.my-domain.com tcp spt:7687 to:192.168.1.1
5 SNAT tcp -- anywhere newdev.my-domain.com tcp spt:dxspider to:192.168.1.1
6 SNAT all -- 192.168.1.0/24 anywhere to:192.168.1.1
  1. 删除其中一个规则
1
2
3
4
5
// 删除nat表PREROUTING中的第一个规则
iptables -t nat -D PREROUTING 1

// 删除nat表中POSTROUTING中的第一个规则
iptables -t nat -D POSTROUTING 1
  1. 添加转发规则
1
2
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 2233 -j DNAT --to-destination 192.168.1.2:2538
iptables -t nat -A POSTROUTING -d 192.168.1.2/32 -p tcp -m tcp --dport 2233 -j SNAT --to-source 192.168.1.1