DNS修改器(linux+win)

前言

有需求:修改DNS服务器,主备两个,要求无脑配置

linux下修改DNS(无需root权限)

常规shell命令方法都需要linux的root权限才能执行,但我发现普通用户在图形界面改DNS也能生效,也就是说通常普通用户也是拥有修改网络配置的权限的,只是不能通过修改系统配置文件来实现,但是有其他方法,如nmcli命令

查看活动的网络连接名称

1
nmcli -t -f NAME con show --active

修改DNS

1
nmcli con mod <connection_name> ipv4.dns <dns_primary>,<dns_secondary>

刷新DNS缓存

1
systemd-resolve --flush-caches

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import subprocess
import time

def set_dns(dns_primary, dns_secondary):
try:
connection_name = subprocess.check_output(['nmcli', '-t', '-f', 'NAME', 'con', 'show','--active']).decode().strip()
subprocess.run(['nmcli', 'con', 'mod', connection_name, 'ipv4.dns', f'{dns_primary},{dns_secondary}'])
subprocess.run(['nmcli', 'con', 'down', connection_name])
subprocess.run(['nmcli', 'con', 'up', connection_name])
subprocess.run(['systemd-resolve', '--flush', 'caches'])
time.sleep(10)
try:
dns_info = subprocess.check_output(['nmcli'], text=True)
if dns_primary in dns_info and dns_secondary in dns_info:
print("设置DNS配置成功")
except subprocess.CalledProcessError as e:
print(f"设置DNS配置失败: {e}")
return False
except subprocess.CalledProcessError as e:
print(f"设置DNS配置失败: {e}")
return False

if __name__ == "__main__":
dns_primary = "114.114.114.114"
dns_secondary = "8.8.8.8"
set_dns(dns_primary, dns_secondary)
input("按任意键退出...")
# pyinstaller --onefile -c --uac-admin --noconfirm setDNS.py

可以用pyinstaller直接打包成linux下的可执行文件

windows下修改DNS(默认使用管理员权限打开)

遍历所有网卡,如果IP是以192开头的,则修改其DNS配置

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import wmi
import re
import os

def set_dns_configuration():
try:
wmiService = wmi.WMI()
colNicConfigs = wmiService.Win32_NetworkAdapterConfiguration(IPEnabled=True)
for colNicConfig in colNicConfigs:
for ip in colNicConfig.ipaddress:
if re.match(r'192\.', ip) is not None:
arrDNSServers = ['114.114.114.114', '8.8.8.8']
returnValue = colNicConfig.SetDNSServerSearchOrder(DNSServerSearchOrder=arrDNSServers)
if returnValue[0] == 0:
print("DNS修改成功")
break
else:
print("DNS修改失败")
flushDNS = "ipconfig /flushdns"
os.system(flushDNS)
print("DNS配置成功")
except Exception as e:
print(f'程序运行错误,原因:{str(e)}')

if __name__ == "__main__":
set_dns_configuration()
input('按下任意键退出')
# pyinstaller --onefile -c --uac-admin --noconfirm set_DNS_win.py
1
pyinstaller --onefile -c --uac-admin --noconfirm set_DNS_win.py

--uac-admin参数表示默认以管理员权限运行


DNS修改器(linux+win)
https://xinhaojin.github.io/2024/09/19/DNS修改器(linux+win)/
作者
xinhaojin
发布于
2024年9月19日
许可协议