重新修改被 VPN 连接之后覆盖的 DNS resolver

WHAT

车间的 办公网 需要拨 VPN 才能访问 线上内网 机器,但在连上 VPN 后发现 /etc/resolv.conf 被修改,导致路由器的科学上网 DNS 被覆盖,域名解析出现问题。

HOW

macOS 的 /etc/resolv.conf 文件是由 scutil 管理的:

$ echo 'list ".*DNS"' | scutil | awk '{print $NF}'
State:/Network/Global/DNS
State:/Network/MulticastDNS
State:/Network/PrivateDNS
State:/Network/Service/com.cisco.anyconnect/DNS

连接 VPN 后 /etc/resolv.conf 路由器的 DNS 被放到最后:

$ scutil
> d.init
> get State:/Network/Global/DNS
> d.show
<dictionary> {
  SearchOrder : 1
  ServerAddresses : <array> {
    0 : 172.16.1.1
    1 : 172.16.1.2
    2 : 192.168.1.1
  }
}
> quit

$ printf 'd.init\nget State:/Network/Global/DNS\nd.show\nquit\n'|scutil
<dictionary> {
  SearchOrder : 1
  ServerAddresses : <array> {
    0 : 172.16.1.1
    1 : 172.16.1.2
    2 : 192.168.1.1
  }
}

写了个脚本通过 scutil 重新修改 /etc/resolv.conf 配置文件:

#!/bin/bash

states=$(echo 'list ".*DNS"' | scutil | awk '{print $NF}')

for state in $states
do
    dns_output=$(printf "d.init\nget ${state}\nd.show\nquit\n" | scutil)

    if echo "$dns_output" | grep -iq 172
    then
        echo -e "__INFO: $state NEED change:\n${dns_output}"
        echo "__INFO: $state UPDATED:"
        printf "d.init\nget ${state}\nd.remove ServerAddress\nd.add ServerAddresses * 192.168.1.1 172.16.1.1 172.16.1.2\nset ${state}\nd.show\nquit\n" | sudo scutil
    else
        :
    fi
done

脚本执行:

$ bash macdns.sh
__INFO: State:/Network/Global/DNS NEED change:
<dictionary> {
  SearchOrder : 1
  ServerAddresses : <array> {
    0 : 172.16.1.1
    1 : 172.16.1.2
    2 : 192.168.1.1

  }
}
__INFO: State:/Network/Global/DNS UPDATED:
<dictionary> {
  SearchOrder : 1
  ServerAddresses : <array> {
    0 : 192.168.1.1
    1 : 172.16.1.1
    2 : 172.16.1.2
  }
}
__INFO: State:/Network/Service/com.cisco.anyconnect/DNS NEED change:
<dictionary> {
  SearchOrder : 1
  ServerAddresses : <array> {
    0 : 172.16.1.1
    1 : 172.16.1.2
    2 : 192.168.1.1
  }
}
__INFO: State:/Network/Service/com.cisco.anyconnect/DNS UPDATED:
<dictionary> {
  SearchOrder : 1
  ServerAddresses : <array> {
    0 : 192.168.1.1
    1 : 172.16.1.1
    2 : 172.16.1.2
  }
}

reference

https://rakhesh.com/powershell/vpn-client-over-riding-dns-on-macos/

https://superuser.com/questions/86184/change-dns-server-from-terminal-or-script-on-mac-os-x

https://apple.stackexchange.com/questions/344232/force-dns-resolution-to-happen-outside-vpn/404838#404838