介紹
通過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 /]#
補充
但是,對於SNAT,不管是幾個地址,必須明確的指定要SNAT的ip
假如當前系統用的是ADSL動態撥號方式,那么每次撥號,出口ip192.168.5.3都會改變
而且改變的幅度很大,不一定是192.168.5.3到192.168.5.5范圍內的地址
這個時候如果按照現在的方式來配置iptables就會出現問題了
因為每次撥號后,服務器地址都會變化,而iptables規則內的ip是不會隨着自動變化的
每次地址變化后都必須手工修改一次iptables,把規則里邊的固定ip改成新的ip
這樣是非常不好用的
假如當前系統用的是ADSL動態撥號方式,那么每次撥號,出口ip192.168.5.3都會改變
而且改變的幅度很大,不一定是192.168.5.3到192.168.5.5范圍內的地址
這個時候如果按照現在的方式來配置iptables就會出現問題了
因為每次撥號后,服務器地址都會變化,而iptables規則內的ip是不會隨着自動變化的
每次地址變化后都必須手工修改一次iptables,把規則里邊的固定ip改成新的ip
這樣是非常不好用的
MASQUERADE就是針對這種場景而設計的,他的作用是,從服務器的網卡上,自動獲取當前ip地址來做NAT
比如下邊的命令:
iptables -t nat -A POSTROUTING -s 10.8.0.0/255.255.255.0 -o eth0 -j MASQUERADE
如此配置的話,不用指定SNAT的目標ip了
不管現在eth0的出口獲得了怎樣的動態ip,MASQUERADE會自動讀取eth0現在的ip地址然后做SNAT出去
這樣就實現了很好的動態SNAT地址轉換
比如下邊的命令:
iptables -t nat -A POSTROUTING -s 10.8.0.0/255.255.255.0 -o eth0 -j MASQUERADE
如此配置的話,不用指定SNAT的目標ip了
不管現在eth0的出口獲得了怎樣的動態ip,MASQUERADE會自動讀取eth0現在的ip地址然后做SNAT出去
這樣就實現了很好的動態SNAT地址轉換