Files
bird_config/route-sync
2026-02-05 00:56:38 +08:00

72 lines
2.1 KiB
Bash
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
set -euo pipefail
MAIN_TABLE="main"
RT_TABLES_FILE="/etc/iproute2/rt_tables"
check_root() {
if [ $EUID -ne 0 ]; then
echo "错误操作路由表需要root权限请使用sudo运行脚本"
exit 1
fi
}
get_custom_tables() {
grep -vE '^#|^$' "${RT_TABLES_FILE}" | awk '{print $1}' | \
grep -E '^[0-9]+$' | grep -v "^${MAIN_TABLE}$" | sort -n | uniq | tr '\n' ' ' | sed 's/ $//'
}
sync_ipv4_routes() {
local custom_tables="$1"
local ipv4_routes
ipv4_routes=$(ip -4 route show table "${MAIN_TABLE}" proto kernel scope link)
local ipv4_count=$(echo "${ipv4_routes}" | grep -c .)
if [ ${ipv4_count} -gt 0 ]; then
echo "${ipv4_routes}" | while read -r route; do
[ -z "${route}" ] && continue
for table in ${custom_tables}; do
ip -4 route replace ${route} table ${table} >/dev/null 2>&1
done
#echo "${route} --> ${custom_tables}"
done
echo "IPv4同步完成,共${ipv4_count}"
else
echo "IPv4无直连路由"
fi
}
sync_ipv6_routes() {
local custom_tables="$1"
local ipv6_routes
ipv6_routes=$(ip -6 route show table "${MAIN_TABLE}" proto kernel metric 256)
local ipv6_count=$(echo "${ipv6_routes}" | grep -c .)
if [ ${ipv6_count} -gt 0 ]; then
echo "${ipv6_routes}" | while read -r route; do
[ -z "${route}" ] && continue
for table in ${custom_tables}; do
ip -6 route replace ${route} table ${table} >/dev/null 2>&1
done
#echo "${route} --> ${custom_tables}"
done
echo "IPv6同步完成,共${ipv6_count}"
else
echo "IPv6无直连路由可同步"
fi
}
main() {
check_root
local CUSTOM_TABLES=$(get_custom_tables)
if [ -z "${CUSTOM_TABLES}" ]; then
echo "提示:${RT_TABLES_FILE}中无自定义路由表已排除254主表退出执行"
exit 0
fi
echo "获取到路由表:${CUSTOM_TABLES}"
sync_ipv4_routes "${CUSTOM_TABLES}"
sync_ipv6_routes "${CUSTOM_TABLES}"
echo "所有路由同步完成!"
}
main