Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Change DNS Servers Programmatically in Windows?

I want to change DNS servers programmatically. I don't want to build a DNS server, I just want to change the primary and secondary dns servers automatically. This work needs to be done in Python.

like image 899
PythEch Avatar asked Feb 22 '23 23:02

PythEch


2 Answers

You can call a command line tool to do it for you with os.system.

import os
os.system('netsh interface ip set dns "Local Area Connection" static 192.168.0.200')
like image 86
Glider Avatar answered Feb 25 '23 15:02

Glider


import os
# The first thing you need to import os and identify is the name of the network interface you want to modify.
# You can find the names of all network interfaces by running the following command:
os.system('netsh interface ipv4 show interfaces')
# for me its "Wi-Fi"
# For the primary DNS server run:
os.system('netsh interface ip set dns name="Wi-Fi" static 185.37.37.37')
# For the secondary DNS server run:
os.system('netsh interface ip add dns name="Wi-Fi"  185.37.39.39 index=2')
# whene you'r done with the DNS server run :
os.system('netsh interface ip set dnsservers name="Wi-Fi" source=dhcp')
#keep in mind  that you need administrator privilege
like image 30
wajdi Avatar answered Feb 25 '23 14:02

wajdi