因公网IPv4地址紧缺,可使用PAT,Dynamic nat进行配置,外网需要访问内网服务器一般使用static nat进行解决
其原理即为替换网络层的Source IP或者Dest IP进行设置,在iptables上实现为postrouting函数中进行替换
[root@localhost ~]# iptables -t nat -A POSTROUTING -s 192.168.103.0/24 ! -d 192.168.103.0/24 -j SNAT --to-source 11.5.1.7
[root@localhost ~]# iptables -vnL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
[root@localhost ~]# iptables -vnL -t nat
Chain PREROUTING (policy ACCEPT 5 packets, 340 bytes)
pkts bytes target prot opt in out source destination
Chain INPUT (policy ACCEPT 5 packets, 340 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 5 packets, 411 bytes)
pkts bytes target prot opt in out source destination
Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
5 411 SNAT all -- * * 192.168.103.0/24 !192.168.103.0/24 to:11.5.1.7
持久保存
[root@localhost ~]# iptables-save > ~/iptables.txt
[root@localhost ~]# cat ~/iptables.txt
# Generated by iptables-save v1.4.21 on Fri May 28 19:18:08 2021
*filter
:INPUT ACCEPT [239:17104]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [126:14756]
COMMIT
# Completed on Fri May 28 19:18:08 2021
# Generated by iptables-save v1.4.21 on Fri May 28 19:18:08 2021
*nat
:PREROUTING ACCEPT [6:716]
:INPUT ACCEPT [7:776]
:OUTPUT ACCEPT [3:228]
:POSTROUTING ACCEPT [0:0]
-A PREROUTING -d 192.168.103.71/32 -p tcp -m tcp --dport 22 -j DNAT --to-destination 192.168.103.71:8080
-A POSTROUTING -s 192.168.103.0/24 ! -d 192.168.103.0/24 -j SNAT --to-source 11.5.1.7
COMMIT
# Completed on Fri May 28 19:18:08 2021
[root@localhost ~]# iptables -F
[root@localhost ~]# iptables-restore < ~/iptables.txt
[root@localhost ~]# iptables -t nat -vnL
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 DNAT tcp -- * * 0.0.0.0/0 192.168.103.71 tcp dpt:22 to:192.168.103.71:8080
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 SNAT all -- * * 192.168.103.0/24 !192.168.103.0/24 to:11.5.1.7
写入rc.local即可