4

linux使用snat转发的问题

 3 years ago
source link: https://www.wencst.com/archives/1446
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

linux使用snat转发的问题

作者: wencst 分类: linux,云计算,架构设计 发布时间: 2019-02-14 11:30 阅读: 1,660 次

在多台主机的情况下,仅有一台主机能够访问外网。为了使很多主机都可以访问外部网络的情况下使用。

期初,我也认为这种场景几乎不可能出现的,除非有特殊的应用场景才可能。其实这种情况其实非常多见,比如我们使用的阿里云服务。为了节省成本,我们买了N多服务器,但只买了少量的IP。在阿里云中,当云主机不绑定IP时,云主机是无法访问外网的,于是就想到了使用SNAT来做转发。

登录到能够访问外网的服务器中

开启IP转发功能

sed -i 's/net.ipv4.ip_forward = 0/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf
执行sysctl -p使之生效。
注意:如果表链的默认规则改成了drop,还需要执行以下命令。默认accept的情况,不需要执行此命令。
iptables -I FORWARD -s 172.16.3.0/24 -j ACCEPT

添加SNAT转换

iptables -t nat -I POSTROUTING -s 172.16.3.0/24 -j SNAT --to-source 172.16.3.2
其中172.16.3.0是VPC的网段,172.16.3.2是绑定了EIP的ECS实例的内网IP。

为其他机器配置转发

在阿里云中,需要在VPC中添加转发路由。
1
在非阿里云中,需要在其他服务器中修改gateway,将gateway指向可以访问外网的服务器IP地址。

保存以上配置

以上配置后,是无法保存到服务器的,当服务器重启时,依然需要重新配置一次。
1.查看是否安装iptables

命令:systemctl status iptables

输出结果表示没有iptables的相关服务,我们需要安装。
注意,在CentOS7 中,即使没有安装iptables服务,我们也是可以使用iptables命令的,所以以上步骤才可以执行成功。
2.安装iptables
命令:yum install iptables-services
3.检查是否安装成功
命令:systemctl status iptables
输出结果表示已经安装了iptables但是还没有启动
4.启动iptables
命令:systemctl enable iptables.service
命令:systemctl start iptables.service
5.关闭SELINUX
这里需要关闭SELINUX,因为当SELINUX不关闭时,iptables不读取配置文件。

临时关闭命令:setenforce 0

永久关闭操作:vi /etc/selinux/config

把红框中SELINUX的修改为“SELINUX=disabled”即可,保存并推出,即关闭成功。

6.保存iptables

命令:service iptables save
注意:在启动iptables服务时,所有以前的配置均被重置,需要重新配置后保存。
清空iptables命令:iptables -F
7.验证保存结果
命令:service iptables restart
如果服务没有保存,则以前的配置不会生效,还需要重新配置。
查看/etc/sysconfig/iptables文件,保存的iptables配置会存储在这个文件中。
查看SNAT配置已被保存在此文件中即可。
命令:service iptables restart
执行此命令后,查看配置是否依然存在:iptables -t nat -nL
sed -i 's/net.ipv4.ip_forward = 1/net.ipv4.ip_forward = 0/g' /etc/sysctl.conf

执行sysctl -p使之生效。

删除iptables方法

当配置错误,或者配置重复时,为了干净整洁,需要删除iptables配置。

删除FORWARD 规则:

命令:
iptables -nL FORWARD --line-number
iptables -D FORWARD 1

删除一条nat 规则  删除SNAT规则
iptables -t nat  -D POSTROUTING  1
iptables -t nat -D POSTROUTING 7
让openstack 虚拟机上网的规则
iptables -t nat -A POSTROUTING -s 172.28.101.111/255.255.255.0 -o ens33 -j MASQUERADE
参考文献:
https://help.aliyun.com/knowledge_detail/38776.html?spm=5176.11065259.1996646101.searchclickresult.4f3134c8BB1PiW
https://blog.csdn.net/qzc70919700/article/details/79784566
https://blog.csdn.net/qq_38570571/article/details/79426553
https://www.cnblogs.com/hixiaowei/p/8954161.html

如果文章对您有用,扫一下支付宝的红包,不胜感激!

欢迎加入QQ群进行技术交流:656897351(各种技术、招聘、兼职、培训欢迎加入)

Leave a Reply Cancel reply

You must be logged in to post a comment.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK