You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python获取Windows系统的DNS服务器IP地址?

提取Windows DNS服务器IP的Python方案

嘿,我来帮你搞定这个DNS服务器IP提取的问题!既然你已经能成功获取本机IP,那DNS的提取其实也有几个实用又靠谱的方法,我给你整理了三种常用方案,涵盖不同场景需求:

方案1:解析ipconfig /all输出(最贴近你熟悉的命令)

因为你已经熟悉ipconfig /all命令,我们可以用Python调用这个命令,然后解析它的输出文本。不过要注意,这个方法会受系统语言影响(比如中文系统里行是“DNS服务器”而非英文的“DNS Servers”),如果你的脚本只在中文环境用,记得把判断条件改成对应中文关键词。

代码示例:

import subprocess

def get_dns_from_ipconfig():
    # 执行ipconfig /all并捕获输出
    try:
        output = subprocess.check_output(["ipconfig", "/all"], text=True, encoding="gbk")
    except subprocess.CalledProcessError as e:
        print(f"执行命令出错: {e}")
        return []
    
    dns_list = []
    is_dns_section = False
    for line in output.splitlines():
        # 匹配DNS服务器行(中文系统用"DNS服务器",英文用"DNS Servers")
        if "DNS服务器" in line:
            is_dns_section = True
            # 提取第一个DNS地址
            dns_ip = line.split(":")[-1].strip()
            if dns_ip:
                dns_list.append(dns_ip)
        elif is_dns_section:
            stripped_line = line.strip()
            # 后续缩进的行如果是IP格式(简单判断含.)就加入列表
            if stripped_line and "." in stripped_line:
                dns_list.append(stripped_line)
            else:
                # 遇到非DNS行就退出当前区域
                is_dns_section = False
    # 去重避免重复条目
    return list(set(dns_list))

# 测试调用
print("DNS服务器列表:", get_dns_from_ipconfig())

方案2:用WMI直接获取(最稳定,不受语言影响)

这个方法通过Windows系统的WMI接口直接查询网络配置,不需要解析文本,兼容性和稳定性都更好。需要先安装wmi库:

pip install wmi

代码示例:

import wmi

def get_dns_via_wmi():
    dns_servers = []
    # 初始化WMI连接
    c = wmi.WMI()
    # 查询所有启用IP的网络适配器
    for adapter in c.Win32_NetworkAdapterConfiguration(IPEnabled=True):
        # DNSServerSearchOrder就是DNS服务器的IP列表
        if adapter.DNSServerSearchOrder:
            dns_servers.extend(adapter.DNSServerSearchOrder)
    # 去重后返回
    return list(set(dns_servers))

# 测试调用
print("DNS服务器列表(WMI):", get_dns_via_wmi())

方案3:读取Windows注册表(无需额外库,标准库搞定)

Windows会把DNS配置存在注册表中,我们可以用Python标准库的winreg直接读取,不需要依赖任何第三方库,非常轻量化。

代码示例:

import winreg

def get_dns_from_registry():
    dns_servers = []
    # 注册表中存储网络接口配置的路径
    reg_path = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
    
    try:
        # 打开根注册表项
        root_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path)
        idx = 0
        while True:
            try:
                # 枚举每个网络接口的子键
                subkey_name = winreg.EnumKey(root_key, idx)
                subkey = winreg.OpenKey(root_key, subkey_name)
                # 读取NameServer值(存储DNS服务器IP,空格分隔多个)
                try:
                    dns_val, _ = winreg.QueryValueEx(subkey, "NameServer")
                    if dns_val:
                        dns_servers.extend(dns_val.split())
                except FileNotFoundError:
                    # 部分接口没有配置DNS,直接跳过
                    pass
                winreg.CloseKey(subkey)
                idx += 1
            except OSError:
                # 枚举完所有子键,退出循环
                break
        winreg.CloseKey(root_key)
        # 去重返回
        return list(set(dns_servers))
    except Exception as e:
        print(f"读取注册表出错: {e}")
        return []

# 测试调用
print("DNS服务器列表(注册表):", get_dns_from_registry())

小建议

如果你的脚本需要跨语言环境运行,优先选WMI或注册表方案,避免解析文本带来的兼容性问题;如果只是临时用且环境固定,解析ipconfig的方法也足够简单。

内容的提问来源于stack exchange,提问作者Abhishek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:17:30