背景:
有一台A服務器不能上網,和B服務器通過內網來連接,B服務器可以上網,要實現A服務器也可以上網。
內網主機: A eth1:172.16.1.8 外網主機: B eth0:10.0.0.6
外網主機: B eth1:172.16.1.6
SNAT:改變數據包的源地址。防火牆會使用外部地址,替換數據包的本地網絡地址。這樣使網絡內部主機能夠與網絡外部通信。
1.在可以上網那台服務器B上,開啟內核路由轉發功能
#臨時 echo 1 > /proc/sys/net/ipv4/ip_forward sysctl -p #永久 echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf sysctl -p
2.在需要通過代理上網服務器A上,查看路由表。並添加默認網關。route add default gw 172.16.1.6
[root@localhost ~]# 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 0 0 0 eth1 0.0.0.0 172.16.1.6 0.0.0.0 UG 0 0 0 eth1
3.可以上網那台服務器B上添加SNAT規則
iptables -t nat -A POSTROUTING -o eth0 -s 172.16.1.0/24 -j SNAT --to 10.0.0.6
4.保存
service iptables save #重啟iptables服務 /etc/init.d/iptables restart
5.驗證是否可以正常上網。
將iptables設置為開機自啟動 [root@lb02 ~]# chkconfig |grep iptables iptables 0:off 1:off 2:on 3:on 4:on 5:on 6:off