网络接口 DNS 修改工具
概述
该 Python 脚本用于在 Windows 系统中获取活动的网络接口,并允许用户修改所选网络接口的 DNS 设置。脚本执行以下操作:
- 检查当前用户是否具有管理员权限。
- 列出所有活动的网络接口及其信息。
- 获取并显示所选接口的当前 DNS 服务器。
- 提供选项以修改 DNS 设置。
使用方法
-
以管理员身份运行脚本:脚本会检查是否具有管理员权限,如果没有,自动提示用户以管理员权限重新运行。
-
获取活动的网络接口:脚本使用 PowerShell 命令获取系统中的活动网络接口,并将其信息以 JSON 格式输出。输出包括接口名称、描述、MAC 地址和链路速度。
-
选择网络接口:如果系统中有多个活动接口,脚本会列出所有接口并要求用户选择一个接口进行操作。
-
显示当前 DNS 设置:脚本会显示所选接口当前的 DNS 服务器地址。
-
修改 DNS 设置:用户可以选择是否将所选接口的 DNS 修改为 Google 的公共 DNS 服务器(8.8.8.8 和 8.8.4.4)。
脚本代码
import subprocess
import ctypes
import sys
import json
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def get_active_interfaces():
try:
cmd = 'powershell -Command "chcp 65001; Get-NetAdapter | Where-Object {$_.Status -eq \\"Up\\"} | Select-Object Name, InterfaceDescription, MacAddress, LinkSpeed | ConvertTo-Json -Depth 1 -Compress"'
output = subprocess.check_output(cmd, shell=True)
try:
output_str = output.decode('utf-8')
except UnicodeDecodeError:
output_str = output.decode(sys.getfilesystemencoding(), errors='ignore')
print(f"Raw output: {output_str}") # Debug output
output_str = output_str.split('\n', 1)[-1].strip()
adapters = json.loads(output_str)
if isinstance(adapters, dict):
adapters = [adapters]
return adapters
except subprocess.CalledProcessError as e:
print(f"获取网络接口时出错:{e}")
return []
except json.JSONDecodeError as e:
print(f"解析网络接口信息时出错:{e}")
print("原始输出:", output_str)
return []
def get_dns_servers(interface_name):
try:
cmd = f'powershell -Command "chcp 65001; Get-DnsClientServerAddress -InterfaceAlias \'{interface_name}\' -AddressFamily IPv4 | Select-Object -ExpandProperty ServerAddresses"'
output = subprocess.check_output(cmd, shell=True)
try:
output_str = output.decode('utf-8')
except UnicodeDecodeError:
output_str = output.decode(sys.getfilesystemencoding(), errors='ignore')
return output_str.strip().split('\r\n')
except subprocess.CalledProcessError:
return []
def change_dns(interface, dns='8.8.8.8'):
commands = [
f'netsh interface ip set dns "{interface}" static {dns}',
f'netsh interface ip add dns "{interface}" 8.8.4.4 index=2'
]
for cmd in commands:
subprocess.run(cmd, shell=True, check=True)
def main():
if not is_admin():
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
input("请按任意键退出...")
return
active_interfaces = get_active_interfaces()
if not active_interfaces:
print("未找到活动网络接口")
input("请按回车键退出...")
return
if len(active_interfaces) == 1:
selected_interface = active_interfaces[0]
else:
print("找到以下活动网络接口:")
for i, interface in enumerate(active_interfaces, 1):
print(f"{i}. {interface['Name']} - {interface['InterfaceDescription']}")
while True:
try:
choice = int(input("请选择要修改DNS的网卡编号: "))
if 1 <= choice <= len(active_interfaces):
selected_interface = active_interfaces[choice - 1]
break
else:
print("无效的选择,请重新输入。")
except ValueError:
print("请输入一个有效的数字。")
interface_name = selected_interface['Name']
current_dns = get_dns_servers(interface_name)
print(f"当前使用的网卡: {interface_name}")
print(f"当前DNS服务器: {', '.join(current_dns)}")
while True:
confirm = input("是否要更改DNS设置?(y/n): ").lower()
if confirm in ['y', 'n']:
break
print("请输入 'y' 或 'n'。")
if confirm == 'y':
try:
change_dns(interface_name)
print(f"成功将 {interface_name} 的DNS更改为8.8.8.8和8.8.4.4")
except subprocess.CalledProcessError as e:
print(f"更改DNS时出错:{e}")
else:
print("操作已取消")
input("请按回车键退出...")
if __name__ == "__main__":
try:
main()
except Exception as e:
print(f"发生错误: {e}")
input("请按任意键退出...")
评论区