Created
January 16, 2021 08:49
-
-
Save iflamed/9e8cab88f7b24780cc9c78994c62c992 to your computer and use it in GitHub Desktop.
ECS 通过 iptables SNAT转发 共享一个IP上网
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 背景: | |
> 有一台A服务器不能上网,和B服务器通过内网来连接,B服务器可以上网,要实现A服务器也可以上网。 | |
内网主机: A eth1:172.16.1.8 | |
外网主机: B eth0:10.0.0.6 外网主机: B eth1:172.16.1.6 | |
SNAT:改变数据包的源地址。防火墙会使用外部地址,替换数据包的本地网络地址。这样使网络内部主机能够与网络外部通信。 | |
## 在可以上网那台服务器B上,开启内核路由转发功能 | |
### 临时 | |
```shell | |
echo 1 > /proc/sys/net/ipv4/ip_forward | |
sysctl -p | |
``` | |
### 永久 | |
```shell | |
echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf | |
sysctl -p | |
``` | |
## 在需要通过代理上网服务器A上,查看路由表。并添加默认网关. | |
```shell | |
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 | |
``` | |
## 可以上网那台服务器B上添加SNAT规则 | |
```shell | |
iptables -t nat -A POSTROUTING -o eth0 -s 172.16.1.0/24 -j SNAT --to 10.0.0.6 | |
``` | |
## 保存 | |
```shell | |
service iptables save | |
#重启iptables服务 | |
/etc/init.d/iptables restart | |
``` |
Author
iflamed
commented
Jan 16, 2021
- CentOS 8 需要启动 firewalld 才可以。
- 无公网IP的机器需要修改默认网关。
查看外网IP地址:
curl ifconfig.me
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment