13
2019
03
13:16:56

iptables 实现内网转发上网



推荐点击下面图片,通过本站淘宝优惠价购买:

image.png

介绍

  通过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 ms64 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
这样是非常不好用的
 
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地址转换


本文链接:https://hqyman.cn/post/324.html 非本站原创文章欢迎转载,原创文章需保留本站地址!

分享到:





休息一下,本站随机推荐观看栏目:


« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

您的IP地址是: