Skip to content

Instantly share code, notes, and snippets.

@iflamed
Created January 16, 2021 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save iflamed/9e8cab88f7b24780cc9c78994c62c992 to your computer and use it in GitHub Desktop.
Save iflamed/9e8cab88f7b24780cc9c78994c62c992 to your computer and use it in GitHub Desktop.
ECS 通过 iptables SNAT转发 共享一个IP上网
# 背景:
> 有一台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
```
@iflamed
Copy link
Author

iflamed commented Jan 16, 2021

公司有个业务是2B的以及日活不大,所以两台服务器搞定,一个6M EIP。两台机器都是CentOS7系统
EIP为 xxx.xxx.xxx.xxx绑在 内网ip为 172.18.30.175的服务器上,内网机器的内网ip为 172.18.30.176。
现在有个问题,更新软件的时候可以将EIP解绑然后重绑在内网机器上。但是每次都这样搞太麻烦了。于是想到了iptables桥接上网。

在带外网的机器上设置iptables规则:

iptables -t nat -A POSTROUTING -s 172.18.30.176 -j SNAT --to 172.18.30.175

如果想让整个内网的机器全部上网,只需要把 -s 172.18.30.176 换成 -s 172.18.30.0/255.255.255.0 或者 -s 172.18.30.0/24 即可

带外网机器上打开转发

首先查看是否已经打开

sysctl -a |grep 'net.ipv4.ip_forward'

如果值为1,则说明已经打开,否则需要修改配置文件 /etc/sysctl.conf
打开该配置文件,找到该参数,使其变为 net.ipv4.ip_forward = 1
然后运行 sysctl -p 使其生效

在内网机器上,设置其网关为 172.18.30.175

vim /etc/sysconfig/network-scripts/ifcfg-eth0

添加
GATEWAY=172.18.30.175
重启网络服务即可: service network restart

最后验证是否可以上网。

@iflamed
Copy link
Author

iflamed commented Jan 16, 2021

  1. CentOS 8 需要启动 firewalld 才可以。
  2. 无公网IP的机器需要修改默认网关。
route add default gw 172.16.1.6

@iflamed
Copy link
Author

iflamed commented Jan 16, 2021

查看外网IP地址:

curl ifconfig.me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment