🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# iptables企业案例-共享上网和端口映射 [TOC] ## 一、 共享上网 ### 1. 准备工作 1)环境模拟 内网服务器停止防火墙服务,关闭内网服务器外网网卡模拟真实环境, 删除内网网卡DNS地址信息,使其不能上网,并配置网关为有外网的服务器[172.16.1.7] ```sh /etc/init.d/iptables stop ifdown eth0 vim /etc/sysconfig/network-scripts/ifcfg-eth1 ``` 网卡配置略 2)查看路由表 ```sh route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 172.16.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1 169.254.0.0 0.0.0.0 255.255.0.0 U 1003 0 0 eth1 0.0.0.0 172.16.1.7 0.0.0.0 UG 0 0 0 eth1 ``` 说明:内网服务器网关地址指定为共享上网服务器内网网卡地址 ### 2. 开启共享上网服务器路由转发功能 ```sh sed i '/net.ipv4.ip_forward/ s#0#1#g' /etc/sysctl.conf grep "_forward" /etc/sysctl.conf net.ipv4.ip_forward = 0 sysctl -p ``` ### 3. 共享上网实现[1:有固定外网IP] 1) 规则配置 ```sh iptables -t nat -A POSTROUTING -s 172.16.1.0/24 -o eth0 -j SNAT --to-source 10.0.0.7 -s 172.16.1.0/24 --- 指定将哪些内网网段进行映射转换 -o eth0 --- 指定在共享上网哪个网卡接口上做NAT地址转换 -j SNAT --- 将源地址进行转换变更 -j DNAT --- 将目标地址进行转换变更 --to-source ip地址 --- 将源地址映射为什么IP地址 --to-destination ip地址 --- 将目标地址映射为什么IP地址 ``` 2) 扩展[] 如果设置forward链默认drop策略,那还需要做如下配置: ```sh iptables -A FORWARD -i eth1 -s 172.16.1.0/24 -j ACCEPT iptables -A FORWARD -o eth0 -s 172.16.1.0/24 -j ACCEPT iptables -A FORWARD -i eth0 -d 172.16.1.0/24 -j ACCEPT iptables -A FORWARD -o eth1 -d 172.16.1.0/24 -j ACCEPT ``` 4. 共享上网实现[2:无固定外网IP] ```sh iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -j MASQUERADE ``` ## 二、端口映射 ### 1.将网关的IP和9000端口映射到内网服务器的22端口 1)映射关系 ```sh 端口映射 10.0.0.7:9000 -->172.16.1.8:22 ``` 2)实现命令 ```sh iptables -t nat -A PREROUTING -d 10.0.0.7 -i eth0 -p tcp --dport 9000 -j DNAT --to-destination 172.16.1.8:22 ``` ### 2. 实现把访问10.0.0.5:80的请求转到172.16.1.8:80 ```sh iptables -t nat -A PREROUTING -d 10.0.0.5 -p tcp --dport 80 -j DNAT --to-destination 172.16.1.8:80 ```