如何配置策略路由实现出口IP随机?
美国、香港服务器
如何配置策略路由实现出口IP随机?
04-25 来源:
Ubuntu 策略路由 实现出口 IP 随机切换(纯系统原生、无需软件)
一、环境前提(必须先做好)
单网卡多 IP(Netplan 已配置完成)
示例参数(你自行替换):
网卡:ens33
网关:192.168.1.1
额外出口 IP:
IP_A:192.168.1.10
IP_B:192.168.1.11
IP_C:192.168.1.12
查看确认:
bash
运行
ip a
二、Step1:自定义路由表
编辑路由表文件:
bash
运行
sudo nano /etc/iproute2/rt_tables
末尾添加:
plaintext
10 tabA
11 tabB
12 tabC
三、Step2:每个 IP 独立路由表 + 源 IP 规则
bash
运行
# 路由表 + 网关
sudo ip route add default via 192.168.1.1 dev ens33 table tabA
sudo ip route add default via 192.168.1.1 dev ens33 table tabB
sudo ip route add default via 192.168.1.1 dev ens33 table tabC
# 绑定 源IP → 对应路由表
sudo ip rule add from 192.168.1.10 table tabA
sudo ip rule add from 192.168.1.11 table tabB
sudo ip rule add from 192.168.1.12 table tabC
四、Step3:核心 ——iptables 随机标记(实现随机)
原理:给新建连接随机打上 10/11/12 标记,不同标记走不同 IP 路由,天然随机。
bash
运行
# 清空旧规则
sudo iptables -t mangle -F
# 随机打标记 10 11 12 对应三张表
sudo iptables -t mangle -A OUTPUT -m statistic --mode random --probability 0.33 -j MARK --set-mark 10
sudo iptables -t mangle -A OUTPUT -m statistic --mode random --probability 0.50 -j MARK --set-mark 11
sudo iptables -t mangle -A OUTPUT -j MARK --set-mark 12
五、Step4:mark 绑定路由表
bash
运行
sudo ip rule add fwmark 10 table tabA
sudo ip rule add fwmark 11 table tabB
sudo ip rule add fwmark 12 table tabC
六、Step5:删除默认路由,纯净随机出口
bash
运行
sudo ip route del default
七、验证是否【随机 IP】
bash
运行
for i in {1..15};do curl -s ifconfig.me; echo; sleep 0.2;done
✅ 结果:IP 杂乱随机出现,不是顺序轮询,就是成功。
八、永久保存(重启不失效)
1. 保存 iptables 规则
bash
运行
sudo apt install iptables-persistent -y
sudo netfilter-persistent save
2. 策略路由开机自启
bash
运行
sudo nano /etc/rc.local
写入所有 ip rule /ip route 命令,最后加:
bash
运行
exit 0
授权:
bash
运行
sudo chmod +x /etc/rc.local
九、快速恢复默认(一键还原)
bash
运行
# 清空iptables标记
sudo iptables -t mangle -F
# 清空策略路由
sudo ip rule del fwmark 10
sudo ip rule del fwmark 11
sudo ip rule del fwmark 12
sudo ip rule del from 192.168.1.10
sudo ip rule del from 192.168.1.11
sudo ip rule del from 192.168.1.12
# 恢复默认网关
sudo ip route add default via 192.168.1.1 dev ens33
三二互联专业提供香港VPS,美国VPS主机,香港云服务器租用等业务香港美国到大陆CN2 GIA速度最快