Skip to content

Instantly share code, notes, and snippets.

@ikorchynskyi
Forked from pyther/wsl_dns.py
Created May 27, 2021 07:30
Show Gist options
  • Save ikorchynskyi/e4ab92e1dc0429deb05d51716e4b1163 to your computer and use it in GitHub Desktop.
Save ikorchynskyi/e4ab92e1dc0429deb05d51716e4b1163 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import argparse
import re
import datetime
import ipaddress
import os
import sys
def get_iface_networks(dev):
# IPv6 is cool, but Nokia doesn't use it
return re.search(re.compile(r'(?<=inet )(.*)(?=\ brd)', re.M), os.popen(f'ip addr show {dev}').read()).groups()
def get_first_network_address(net):
# Expects IP/Netmask (172.16.20.164/28)
return ipaddress.IPv4Interface(net).network[1]
def get_default_gateway():
return re.search(re.compile(r'via ([0-9.]+)', re.M), os.popen(f'ip route list default').read()).groups()[0]
def generate_resolv(servers, search_list):
out = []
out.append(f"# Generated by {sys.argv[0]} at {str(datetime.datetime.now())}")
for x in servers:
out.append(f"nameserver {x}")
if search_list:
search_str = ','.join(search_list)
out.append(f"search {search_str}")
out.append("options timeout:1 retries:1")
return '\n'.join(out)
def write_resolv(data):
with open('/etc/resolv.conf', 'w') as fd:
fd.write(data)
fd.write('\n')
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--servers', type=str, help="dns servers")
parser.add_argument('--search', type=str, help="dns search suffix")
args = parser.parse_args()
# Assumes we only have one IP configured on the Linux eth0 interface
eth0_network = get_iface_networks('eth0')[0]
eth0_gateway = str(get_first_network_address(eth0_network))
default_gateway = get_default_gateway()
# Sanity Checks
if eth0_gateway != default_gateway:
print("Warning: default gateway does not match guessed gateway of eth0")
print("Warning: script makes assumptions that may not be true on your system!")
servers = []
search = []
if args.servers:
servers = args.servers.split(',')
servers += [eth0_gateway]
if args.search:
search = args.search.split(',')
config = generate_resolv(servers, search)
print("Generated resolv.conf")
print(config)
write_resolv(config)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment