Linux中使用iptables做SNAT代理访问互联网

小柒博客 Linux评论322字数 1187阅读3分57秒阅读模式

一、环境准备

序号

IP地址

用途

1

192.168.56.136

代理服务器

2

192.168.56.138

Linux客户端

注:192.168.56.138不能上外网,192.168.56.136与192.168.56.138内网相通;192.168.56.136可以正常上外网。实现需求让192.168.56.138也能上外网。

1、NAT简介

NAT 全名是 Network Address Translation,字面上的意思是网络地址转换,它还可以分为源地址转换(SNAT)和目的地址转换(DNAT)。SNAT 主要是用来给内网的主机提供连接到 Internet 的默认网关,而 DNAT 主要将内网机器的端口映射到外网上面。

二、iptables配置SNAT规则

1、配置内核转发

[root@localhost ~]# vim /etc/sysctl.conf

net.ipv4.ip_forward = 1

[root@localhost ~]# sysctl -p

net.ipv4.ip_forward = 1

2、iptables添加SNAT规则

[root@localhost ~]# iptables -t nat -A POSTROUTING -s 192.168.56.0/255.255.255.0 -o en333 -j MASQUERADE

或者

[root@localhost ~]# iptables -t nat -A POSTROUTING -o ens33 -s 192.168.56.0/24 -j SNAT --to 192.168.56.136

3、保存添加的iptables规则

[root@localhost ~]# service iptables save

iptables: Saving firewall rules to /etc/sysconfig/iptables:[ OK ]

4、在Linux客户端配置网关

[root@localhost ~]# route add default gw 192.168.56.136

5、查看路由表

[root@localhost ~]# route -ne

Kernel IP routing table

Destination      Gateway             Genmask          Flags    MSS    Window   irtt       Iface

0.0.0.0             192.168.56.136  0.0.0.0              UG       0          0               0       ens33

192.168.56.0    0.0.0.0               255.255.255.0   U         0          0               0       ens33

6、验证是否可以上外网

[root@localhost ~]# ping baidu.com

[root@localhost ~]# curl -I https://www.baidu.com

验证结果:可以正常访问外网。

若文章图片、下载链接等信息出错,请在评论区留言反馈,博主将第一时间更新!如本文“对您有用”,欢迎随意打赏,谢谢!

继续阅读
Wechat
微信扫一扫,加我!
weinxin
微信公众号
微信扫一扫,关注我!
weinxin
小柒博客
  • 本文由 小柒博客 发表于 2023年7月12日11:14:00
  • 声明:本站所有文章,如无特殊说明或标注,本站文章均为原创。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。转载请务必保留本文链接:https://www.yangxingzhen.com/9388.html
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

拖动滑块以完成验证