环境准备
- 路由系统:openwrt 20.02
- 加速节点:openvpn
- IP分类: IANA组织公示地址
1、通过iptables
实现智能分流
1.1 开启流量转发
$ cat /etc/sysctl.d/30-ipforward.conf
net.ipv4.ip_forward=1
net.ipv6.conf.all.forwarding = 1
net.ipv4.tcp_congestion_control=westwood
net.ipv4.tcp_syn_retries = 5
net.ipv4.tcp_synack_retries = 5
编辑完成后,执行以下命令使变动立即生效
$ sysctl -p
1.2 下载ip地址表
wget -c http://ftp.apnic.net/stats/apnic/delegated-apnic-latest
cat delegated-apnic-latest | awk -F '|' '/CN/&&/ipv4/ {print $4 "/" 32-log($5)/log(2)}' | cat > cn_rules.conf
1.3 创建ipset,将下载好的IP导入到ipset中
ipset create -n china hash:net maxelem 65536
for ip in $(cat cn_rules.conf); do ipset add china $ip; done
# 查看
ipset list china
1.4 创建路由策略
ip route add 0.0.0.0/0 dev tun0 table tunnel
ip route show table main | grep -Ev ^default | while read ROUTE ; do ip route add table tunnel $ROUTE ; done
1.5 将符合规则的流量打上标记,并在mangle表中处理标记
# 打标记
iptables -t mangle -A PREROUTING -m set ! --match-set china dst -j MARK --set-mark 1
# GitHub访问加速
iptables -t mangle -R PREROUTING 1 -m set ! --match-set china dst -j MARK --set-mark 1
注:tun0网卡为连接海外节点的vpn隧道,具体部署再次不在赘述
2、通过策略路由实现智能分流
# GitHub加速
GATEWAY_IP=$(ip route|grep "default"|awk '{print $3}') # 网关IP
TUN_IP=$(ifconfig tun0 | awk -F '[ :]+' 'NR==2 {print $4}') # tun0网卡IP
ip route del default via "$GATEWAY_IP"
ip route add "$VPN_SERVER" via "$TUN_IP"
# 特殊ip段走网关的IP地址
ip route add "192.168.0.0/16" via "$GATEWAY_IP"
ip route add "172.16.0.0/16" via "$GATEWAY_IP"
for i in $(cat /usr/local/sdwan/config/cn_rules.conf)
do
ip route add "$i" via "$GATEWAY_IP"
done
ip route del "0.0.0.0/1"
ip route add "0.0.0.0/1" via "$GATEWAY_IP"
注:此教程仅提供思路,具体实现方法请结合实际环境做调整