Skip to content

Instantly share code, notes, and snippets.

@ezr
Created June 7, 2021 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezr/9cb3f6537a80be638c90b289a19c9b3e to your computer and use it in GitHub Desktop.
Save ezr/9cb3f6537a80be638c90b289a19c9b3e to your computer and use it in GitHub Desktop.
A script to change DNS servers when using systemd-resolved
#!/usr/bin/env python3
from os import listdir
from pydbus import SystemBus
import socket
nics = listdir("/sys/class/net/")
nics.remove("lo")
for idx, nic in enumerate(nics):
print(idx, nic)
nic_choice_input = input("Which NIC to apply to? ")
if nic_choice_input.isdigit():
nic_choice = nics[int(nic_choice_input)]
else:
nic_choice = nic_choice_input
dns_servers = [
"1.0.0.1 1.1.1.1",
"8.8.4.4 8.8.8.8",
"8.8.4.4 1.0.0.1",
"9.9.9.9 149.112.112.112",
"208.67.222.222 208.67.220.220"
]
for idx, server in enumerate(dns_servers):
print(idx, server)
servers_choice_input = input("Which server? ")
if servers_choice_input.isdigit():
servers_choice = dns_servers[int(servers_choice_input)].split(" ")
else:
servers_choice = servers_choice_input.split(" ")
# https://www.freedesktop.org/wiki/Software/systemd/resolved/
# https://wiki.freedesktop.org/www/Software/systemd/writing-network-configuration-managers/
system_bus = SystemBus()
resolve = system_bus.get("org.freedesktop.resolve1", "/org/freedesktop/resolve1")
with open("/sys/class/net/%s/ifindex" % nic_choice, "r") as f:
ifindex = int(f.read())
servers = list(map(lambda ip: (socket.AF_INET, socket.inet_aton(ip)), servers_choice))
resolve.RevertLink(ifindex) # to clear out previously configured servers
resolve.SetLinkDNS(ifindex, servers)
@ezr
Copy link
Author

ezr commented Jun 7, 2021

This is just like running # resolvectl dns INTERFACE SERVERS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment