The problem

I have got different DNS servers on my Windows computer, depending on the location I am currently at: If I am in the office then there are the company DNS servers. If I am at home, then my home DNS server should be used.

Sadly, WSL seems to be unable to update the DNS servers on it’s own. I am not quite sure why that is, but I found a way around it.

Requirements

I will use an external library: dns.resolver. I installed that one via Conda: conda install -n dns-resolver dnspython.

The code

#!/home/chris/.conda/envs/dns-resolver/bin/python

import shutil
import subprocess

import dns.resolver

DOMAIN = "domain.com"

servers = subprocess.check_output(["/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", "(Get-DnsClientServerAddress -AddressFamily IPv4).ServerAddresses"])
servers = servers.decode("utf8").split("\r\n")

print("Found servers:", servers)

resolver = dns.resolver.Resolver()

available_servers = []

shutil.move("/etc/resolv.conf", "/etc/resolv.conf.bak")

print("Testing servers.")

for server in set(servers):
    if not server.strip():
        continue

    print(f"{server}... ", end="")

    resolver.nameservers = [server]

    try:
        resolver.resolve(DOMAIN)
    except dns.resolver.LifetimeTimeout:
        print("not reachable.")
        continue

    print("reachable.")
    available_servers.append(server)

    with open("/etc/resolv.conf", "a") as fout:
        fout.write(f"nameserver {server}\n")

print("Done!")

The concept

I will first let Powershell list all the DNS servers that are currently defined in some networks. On my company device, not all those DNS servers are actually reachable - for example, the VPN network has got predefined DNS servers which will also be defined here but unavailable if I am not connected to VPN.

So the second step is the following: Loop through the list of all those DNS servers and try to resolve some domain name. If so, write the DNS record into the /etc/resolv.conf file.

Note the set(servers) in line $23$: For different interfaces (for example, LAN and WiFi), the same DNS servers may be used. With the set, I won’t check the same DNS server twice.