如何通过特定网关路由给定主机名的所有 IPv4

这对于例如绕过特定主机的 VPN 很有用。

有关具有单个 IP 地址的主机的简化方法,请参见 Linux:如何绕过 VPN 路由特定主机

add_routes_for_host.sh

add_routes_for_host() {
    local hostname="$1"
    local gateway="$2"
    local metric="$3"

    # Get all IPv4 addresses for the hostname
    local ips=$(dig +short "$hostname" A | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$')

    if [ -z "$ips" ]; then
        echo "No IPv4 addresses found for $hostname"
        return 1
    fi

    # Add route for each IP
    for ip in $ips; do
        if [ -z "$ip" ]; then
            continue
        fi

        if sudo ip route add "$ip/32" via "$gateway" metric "$metric"; then
            echo "Added route for $ip via $gateway"
        else
            echo "Failed to add route for $ip"
        fi
    done
}

示例用法

add_routes_for_host_usage.sh
add_routes_for_host "security.ubuntu.com" "192.168.1.1" "10"

Check out similar posts by category: Networking, Linux