iptables共享上网
1.1 流程大概如下:
1.环境准备
内部服务器B
内网172.16.1.12 ifdown eth0 #首先关闭外网网卡 route add default gw 172.16.1.11 #把上图中的eth1设置为B的网关 添加dns [root@web01 ~]# cat /etc/resolv.conf nameserver 192.168.56.2
.测试:
ping www.baidu.com ping 203.81.19.1 结果应该是不通。
网关服务器
eth0:192.168.56.11 eth1:172.16.1.11 gw: 192.168.56.2 #网关为 修改内核转发: 内核文件/etc/sysctl.conf里开启转发功能。 在服务器网关A 192.168.56.11机器上开启路由转发功能。 编辑/etc/sysctl.conf修改内容为net.ipv4.ip_forward = 1,然后执行sysctl -p使修改生效。 [root@oldboy ~]# sysctl -p net.ipv4.ip_forward = 1 测试:ping www.baidu.com 结果通。 调整iptables环境(初始化环境) iptables -P INPUT ACCEPT iptables -P FORWARD ACCEPT iptables -F
然后执行
iptables -t nat -A POSTROUTING -s 172.16.1.0/24 -o eth0 -j SNAT --to-source 192.168.56.11
方法1:适合于有固定外网地址的:
iptables -t nat -A POSTROUTING -s 172.16.1.0/24 -o eth0 -j SNAT --to-source 192.168.56.11
方法2:适合变化外网地址(拨号上网):
iptables -t nat -A POSTROUTING -s 172.16.1.0/24 -j MASQUERADE ##伪装。
保存规则
#/etc/init.d/iptables save iptables: Saving firewall rules to /etc/sysconfig/iptables:[ OK ] #cat /etc/sysconfig/iptables # Generated by iptables-save v1.4.7 on Wed May 30 14:02:24 2018 *nat :PREROUTING ACCEPT [7:728] :POSTROUTING ACCEPT [2:135] :OUTPUT ACCEPT [2:135] -A POSTROUTING -s 172.16.1.0/24 -o eth0 -j SNAT --to-source 192.168.56.11 COMMIT # Completed on Wed May 30 14:02:24 2018 # Generated by iptables-save v1.4.7 on Wed May 30 14:02:24 2018 *filter :INPUT ACCEPT [436:38213] :FORWARD ACCEPT [28:2352] :OUTPUT ACCEPT [312:33589] COMMIT # Completed on Wed May 30 14:02:24 2018
在内部服务器测试可以ping通说明正常
到这里就完成了