如果使用 NetworkManager,可以把以下脚本放到 /etc/NetworkManager/dispatcher.d/ 并加上执行权限,实现自动设置 ip rule:
#!/bin/bash
[ "$1" == "wg0" ] || exit
TABLE_ID=20
function update_routing_table() {
IP_ADDR="${IP4_ADDRESS_0%/*}"
ip route add default via ${IP4_GATEWAY} dev ${DEVICE_IP_IFACE} table ${TABLE_ID}
ip rule add from ${IP_ADDR} table ${TABLE_ID}
}
function clear_routing_table() {
ip rule del lookup ${TABLE_ID}
ip route flush table ${TABLE_ID}
}
case "$2" in
up)
update_routing_table
;;
down)
clear_routing_table
;;
*)
;;
esac
请按需要修改其中的 [ "$1" == "wg0" ]。这个脚本修改自
https://gist.github.com/dcode/bbf990ea781bed1e42d39e2351b6c432