介绍
通过iptables做nat转发实现所有内网服务器上网。
操作
首先开启可以上网的服务器上的内核路由转发功能。这里我们更改/etc/sysctl.conf 配置文件。
[root@web1 /]# sed -i '$a net.ipv4.ip_forward = 1' /etc/sysctl.conf [root@web1 /]# 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@web1 /]# sysctl -p net.ipv4.ip_forward = 1
在能上网的机器上添加SNAT规则(cenots7也可以,好像会自己转化)
清空NAT表规则,如果你有自己的规则谨慎操作。没用的删了就可以 [root@web1 ~]# iptables -t nat -F [root@web1 ~]# iptables -t nat -X [root@web1 ~]# iptables -t nat -Z [root@web1 ~]# iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 118.186.61.82 [root@web1 /]# iptables -t nat -nL Chain PREROUTING (policy ACCEPT) target prot opt source destination Chain INPUT (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination Chain POSTROUTING (policy ACCEPT) target prot opt source destination SNAT all -- 0.0.0.0/0 0.0.0.0/0 to:118.186.61.82
在不能上网的机器上添加缺省路由指到能上网的机器上。
查看一下route命令是哪个包里面的 [root@web1 ~]# rpm -qf /sbin/route net-tools-1.60-114.el6.x86_64 添加缺省路由 [root@web2 /]# route add default gw 10.1.1.1 测试 [root@web2 /]# ping www.baidu.com PING www.a.shifen.com (61.135.169.125) 56(84) bytes of data. 64 bytes from 61.135.169.125 (61.135.169.125): icmp_seq=1 ttl=50 time=3.02 ms 64 bytes from 61.135.169.125 (61.135.169.125): icmp_seq=2 ttl=50 time=3.14 ms ^C --- www.a.shifen.com ping statistics --- 2 packets transmitted, 2 received, 0% packet loss, time 1001ms rtt min/avg/max/mdev = 3.023/3.084/3.146/0.082 ms [root@web2 /]#