iptables的SNAT和DNAT
一、iptables NAT策略
1、SNAT
- 源地址转换,Source Network Address Translation,典型应用环境(局域网主机共享单个公网IP地址接入Internet)
- 前提条件
- 局域网各主机正确设置IP地址/子网掩码
- 局域网各主机正确设置默认网关地址
- Linux网关支持IP路由转发
- 实现方式
- 开启IPv4转发
#开启转发
[root@localhost ~]# echo net.ipv4.ip_forward = 1 >> /etc/sysctl.conf
#查看开启成功没
[root@localhost ~]# cat /etc/sysctl.conf
# sysctl settings are defined through files in
# /usr/lib/sysctl.d/, /run/sysctl.d/, and /etc/sysctl.d/.
#
# Vendors settings live in /usr/lib/sysctl.d/.
# To override a whole file, create a new file with the same in
# /etc/sysctl.d/ and put new settings there. To override
# only specific settings, add a file with a lexically later
# name in /etc/sysctl.d/ and put new settings there.
#
# For more information, see sysctl.conf(5) and sysctl.d(5).
net.ipv4.ip_forward = 1
- 防火墙允许转发
[root@localhost ~]# iptables -I FORWARD -p tcp -j ACCEPT
- 配置SNAT
[root@localhost ~]# iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o ens33 -j SNAT --to-source 218.29.30.31
#ens33入站网卡
-
地址伪装(MASQUERADE)
-
适用于外网IP地址非固定的情况
-
对于ADSL拨号连接,接口通常为 ppp0、ppp1
-
将SNAT规则改为MASQUERADE即可
[root@localhost ~]# iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o ens33 -j MASQUERADE
2、DNAT
- 目标地址转换,Destination Network Address Translation,典型应用环境(在Internet中发布位于企业局域网内的服务器)
- 前提条件
- 局域网的Web服务器能够访问Internet
- 网关的外网IP地址有正确的DNS解析记录
- Linux网关支持IP路由转发
- 实现方式
- 开启 IPv4 转发
#开启转发
[root@localhost ~]# echo net.ipv4.ip_forward = 1 >> /etc/sysctl.conf
#查看开启成功没
[root@localhost ~]# cat /etc/sysctl.conf
# sysctl settings are defined through files in
# /usr/lib/sysctl.d/, /run/sysctl.d/, and /etc/sysctl.d/.
#
# Vendors settings live in /usr/lib/sysctl.d/.
# To override a whole file, create a new file with the same in
# /etc/sysctl.d/ and put new settings there. To override
# only specific settings, add a file with a lexically later
# name in /etc/sysctl.d/ and put new settings there.
#
# For more information, see sysctl.conf(5) and sysctl.d(5).
net.ipv4.ip_forward = 1
- 防火墙允许转发
[root@localhost ~]# iptables -I FORWARD -p tcp -j ACCEPT
- 配置 DNAT
[root@localhost ~]# iptables -t nat -A PREROUTING -i ens33 -d 218.29.30.69 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.88
#ens33 入站网卡
#发布时修改目标端口
[root@localhost ~]# iptables -t nat -A PREROUTING -i ens33 -d 218.29.30.69 -p tcp --dport 2346 -j DNAT --to-destination 192.168.1.88:22