1. 本次实验以centos 7.6为例,是通过将ip rule和iptables结合实现,所以适用于大部分Linux系统,实验过程中共使用两块网卡完成。
网卡名称 | 内网IP | 掩码 | 外网IP |
---|---|---|---|
eth0 | 172.17.80.95 | 255.255.240.0 | 101.34.176.251 |
eth1 | 172.17.254.15 | 255.255.255.0 | 1.117.174.54 |
首先根据腾讯云官网文档《Linux 云服务器配置弹性网卡》(https://cloud.tencent.com/document/product/576/59353)将主辅网卡配置完成并正常通过公网访问,这里配置主辅网卡采用文档中的脚本方式快速配置。
wget https://iso-1255486055.cos.ap-guangzhou.myqcloud.com/nic-hotplug.tgz
tar -zxvf nic-hotplug.tgz
cd nic-hotplug
chmod +x ./install.sh
./install.sh
修改/etc/sysctl.conf中 net.ipv4.ip_forward = 1,修改完成后,执行sysctl -p生效。
#以上命令执行完成重启服务器使配置生效
reboot
复制
修改/etc/sysctl.conf
[root@VM-80-95-centos ~]# vim /etc/sysctl.conf
net.ipv4.ip_forward = 1
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.rp_filter = 0
net.ipv4.conf.eth0.rp_filter = 0 #eth0
net.ipv4.conf.eth1.rp_filter = 0 #eth1
复制
1. 使用 ip rule 分别给两个标记值各指定好路由表。使用`ip rule`默认路由表的权重是 32767。
[root@VM-80-95-centos ~]# ip rule
0: from all lookup local
32766: from all lookup main
32767: from all lookup default
复制
2. 我们需要实现根据数据包上包含的标记值决定数据包的出口路线。所以得让数据包先走现在定义的的路由表,所以需要把它们的权重调得高一些(例如 30000),标记位 100 的数据包走 222 号路由表,标记位 101 的数据包使用 333 号路由表,权重都设置为 30000,当连接增加时,可以继续增加标记位以及对应的路由表。
ip rule add fwmark 100 table 222 prio 30000
ip rule add fwmark 101 table 333 prio 30000
复制
3. 向先前路由表中添加路由。通过命令 ip route查询系统当前路由情况。
ip route add 172.17.80.0/20 dev eth0 table 222
ip route add default via 172.17.80.1 table 222
ip route add 172.17.254.0/24 dev eth1 table 333
ip route add default via 172.17.254.1 table 333
复制
4. 配置iptable 策略,对上行数据包进行分流,然后下行数据包就按照上行出口回包,如果当前连接已经被标记,就把标记位设置到当前的数据包上,如果数据包已经有标记,就放行。
iptables -t mangle -A OUTPUT -j CONNMARK --restore-mark
iptables -t mangle -A OUTPUT -m mark ! --mark 0 -j ACCEPT
复制
这里数据包如果没有被标记,就把数据包标记位设置为 100,每 2个包设置一次标记位为 101
iptables -t mangle -A OUTPUT -j MARK --set-mark 100
iptables -t mangle -A OUTPUT -m statistic --mode nth --every 2 --packet 0 -j MARK --set-mark 101
# 如果是三个出口的情况,这里可以类似于下面增加标记位,本次实验只有两张网卡,不需要再增加标记位 102
# iptables -t mangle -A OUTPUT -m statistic --mode nth --every 3 --packet 1 -j MARK --set-mark 102
复制
被标记数据包的被存到整条连接上,这样两张网卡上的数据包都会使用同一出口。
iptables -t mangle -A OUTPUT -j CONNMARK --save-mark
复制
此外,还需要让数据包上标识的出口是正确的出口。
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
复制
查询以上设置规则。
iptables -L OUTPUT -t mangle
复制
[root@VM-80-95-centos ~]# curl ip.sb
1.117.174.54
[root@VM-80-95-centos ~]# curl ip.sb
1.117.174.54
[root@VM-80-95-centos ~]# curl ip.sb
1.117.174.54
[root@VM-80-95-centos ~]# curl ip.sb
101.34.176.251
[root@VM-80-95-centos ~]# curl ip.sb
101.34.176.251
[root@VM-80-95-centos ~]# curl ip.sb
101.34.176.251
复制
至此,配置完成。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。