VMware实现iptables NAT及端口映射( 二 )


iptables -t nat -A POSTROUTING -s 172.16.10.0/24 -j SNAT --to 10.0.0.5
这条规则做了一个SNAT,也就是源地址转换,将来自172.16.10.0/24的地址转换为10.0.0.5 。
 
有这几条规则,一个简单的nat路由器就实现了 。这时你可以将允许访问的ip或网段添加至FORWARD链,他们就能访问internet了 。
iptables -A FORWARD -s 172.16.10.10 -j ACCEPT # 允许单个地址 或者如下命令
iptables -A FORWARD -s 172.16.10.0/24 -j ACCEPT # 允许该网段
比如我想让172.16.10.10这个地址访问internet,那么你就加如上的命令就可以了 。
 
3、保存iptables规则
iptables-save > /etc/sysconfig/iptables
4.4. 内部服务器node01测试[root@InnerNode01 ~]# ping www.baidu.com # 查看是否可以ping通
PING www.a.shifen.com (180.97.33.108) 56(84) bytes of data.
64 bytes from 180.97.33.108 (180.97.33.108): icmp_seq=1 ttl=127 time=43.4 ms
64 bytes from 180.97.33.108 (180.97.33.108): icmp_seq=2 ttl=127 time=42.6 ms
64 bytes from 180.97.33.108 (180.97.33.108): icmp_seq=3 ttl=127 time=42.1 ms
^C
--- www.a.shifen.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2005ms
rtt min/avg/max/mdev = 42.114/42.735/43.420/0.561 ms
[root@InnerNode01 ~]#
[root@InnerNode01 ~]# telnet www.baidu.com 80 # telnet 是否可行
Trying 112.34.112.40...
Connected to www.baidu.com.
Escape character is '^]'.
 
5. 端口转发5.1. 网络架构

VMware实现iptables NAT及端口映射

文章插图
 
 
5.2. 端口转发需求介绍内部机器1个网络接口
Lan内web server: 172.16.10.10:80
 
网关2个网络接口
Lan口:172.16.10.5/24 eth0
Wan口:10.0.0.5/24 eth1
目的:对内部server进行端口转发,实现internet 10.0.0.8(网段:10.0.0.0/24)用户【模拟外网机器】访问内网服务器172.16.10.10:80 。
 
5.3. 网关服务器操作1、网关机器开启linux的转发功能
[root@gateway01 ~]# tail /etc/sysctl.conf # 添加如下内容
…………
net.ipv4.ip_forward = 1
[root@gateway01 ~]# sysctl -p # 生效
2、网关机器iptables操作
iptables -P FORWARD DROP
将FORWARD链的策略设置为DROP,这样做的目的是做到ip的控制,你允许哪一个访问就可以增加一个规则,不在规则中的ip将无法访问 。
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
这条规则规定允许任何地址到任何地址的确认包和关联包通过 。一定要加这一条,否则你只允许lan IP访问没有用 。
iptables -t nat -A PREROUTING -d 10.0.0.5 -p tcp --dport 80 -j DNAT --to 172.16.10.10:80
如果你要把访问 10.0.0.5:80 的数据包转发到Lan内web server,用上面的命令 。
 
好了,命令完成了,端口转发也做完了,本例能不能转发呢?不能,为什么呢?我下面分析一下 。
本例中我们的FORWARD策略是DROP 。那么也就是说,没有符合规则的包将被丢弃,不管内到外还是外到内 。因此,我们需要加入下面的规则 。
iptables -A FORWARD -d 172.16.10.10 -p tcp --dport 80 -j ACCEPT
 
3、保存iptables规则
iptables-save > /etc/sysconfig/iptables
5.4. 操作验证1、在内部服务器监听80端口
## xshell标签1操作
[root@InnerNode01 ~]# nc -l 80 # 保持持续监听
## xshell标签2操作
[root@InnerNode01 ~]# netstat -lntup
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 808/rpcbind
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1971/nc ### 可见80端口已经监听成功
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1099/sshd
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1355/master
2、在外网服务器Telnet
[zhang@internet01 ~]$ telnet 10.0.0.5 80
Trying 10.0.0.5...
Connected to 10.0.0.5.
Escape character is '^]'.
^]
telnet> quit
Connection closed.
由上可知,外网服务器(10.0.0.8)访问内部服务器(172.16.10.10:80)成功 。
 
 




推荐阅读