如何在Windows中程序化更改DNS服务器?

5 投票
2 回答
6513 浏览
提问于 2025-04-17 02:17

我想要通过编程的方式来更改DNS服务器。我并不想自己搭建一个DNS服务器,我只是想自动更改主DNS和备用DNS服务器。这项工作需要用Python来完成。

2 个回答

3

在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这些问题可能是因为我们写的代码有bug,或者是因为我们没有正确理解某些概念。

当你在编程时,遇到问题不要着急。首先,可以尝试仔细检查你的代码,看看有没有拼写错误或者遗漏的部分。其次,可以查阅一些资料,看看别人是怎么解决类似的问题的。

如果你还是找不到解决办法,可以考虑向社区求助,比如在StackOverflow上提问。在提问时,记得把你的代码和遇到的问题描述清楚,这样别人才能更好地帮助你。

总之,编程是一门需要不断学习和实践的技能,遇到问题是很正常的,保持耐心,慢慢来,你一定能找到解决办法。

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
7

你可以使用 os.system 来调用一个命令行工具,让它为你完成这个任务。

import os
os.system('netsh interface ip set dns "Local Area Connection" static 192.168.0.200')

撰写回答