← 返回首页

通过 .sh 脚本在 Linux 上添加路由

NetRoute Pro 生成包含 ip route add 命令的简单 Bash 脚本。一条命令即可应用。持久化根据发行版需一步额外操作。

准备工作

步骤 1. 在 NetRoute Pro 中生成 .sh

  1. 在 Chrome 中打开目标网站
  2. 启动 NetRoute Pro,选择 Linux 平台
  3. 设置 VPN 接口的 IP 作为网关(例如 10.8.0.1
  4. 选择聚合掩码(推荐 /24
  5. 点击 Analyze Website
  6. 下载 routes.sh
提示:启用 RIPE BGP 优化 — 它会用公告的 BGP 前缀替换单个 IP,当 CDN 轮换地址时路由保持有效。

步骤 2. 应用脚本

chmod +x routes.sh
sudo bash routes.sh

路由立即应用,一直保留到下次重启。要使路由在重启后保留,请执行步骤 3。

步骤 3. 使路由持久化

根据您的发行版选择方法:

systemd-networkd

创建 drop-in 文件 /etc/systemd/network/10-vpn.network.d/routes.conf

[Route]
Destination=104.21.32.0/24
Gateway=10.8.0.1

[Route]
Destination=172.67.0.0/16
Gateway=10.8.0.1

应用:

sudo systemctl restart systemd-networkd

NetworkManager dispatcher

创建脚本 /etc/NetworkManager/dispatcher.d/99-vpn-routes(不要忘记可执行位):

#!/bin/bash
# $1 — interface, $2 — action
if [ "$1" = "wg0" ] && [ "$2" = "up" ]; then
    /usr/local/bin/routes.sh
fi
sudo chmod +x /etc/NetworkManager/dispatcher.d/99-vpn-routes

@reboot cron(最简单、通用)

先将 .sh 移至系统路径:

sudo mv routes.sh /usr/local/bin/routes.sh
sudo chmod +x /usr/local/bin/routes.sh

然后编辑 root crontab:

sudo crontab -e

添加行:

@reboot /usr/local/bin/routes.sh

验证

ip route show | grep 10.8.0.1

您应该看到所有通过 VPN 网关路由的子网。

回滚

生成反向脚本 — 复制 routes.sh 并将所有 ip route add 替换为 ip route del,然后以 root 运行:

sudo bash routes-undo.sh

常见问题

Network is unreachable

VPN 接口未启动或没有 IP。检查:

ip link show
ip addr show

RTNETLINK answers: File exists

此路由已存在。先删除它:

sudo ip route del <subnet>

Permission denied

修改路由表需要 root 权限。使用 sudo 运行脚本。

官方文档

准备好尝试了吗?

NetRoute Pro — 免费的 Chrome 扩展,可从任何网站生成路由。

安装扩展