如何使用Python显示DNS?能否借助psutil实现类似ipconfig /displaydns的功能?
Hey there! Let's tackle your questions about retrieving DNS info with Python, no messy cmd processes required.
1. 如何使用Python实现DNS信息的显示?
The approach here depends on your operating system, since DNS configurations and caches are stored differently across platforms:
On Linux/macOS
- You can read the system's DNS resolver config directly from
/etc/resolv.confusing basic file operations:
with open('/etc/resolv.conf', 'r') as f: dns_config = f.read() print("DNS Resolver Config:\n", dns_config)
- To get the DNS servers actively used for domain resolution, you can also leverage the
socketmodule:
import socket def get_active_dns_servers(): # Query a dummy domain to trigger resolver lookup resolver_info = socket.getaddrinfo('example.com', None) # Extract unique DNS server IPs from the results dns_servers = {res[4][0] for res in resolver_info} return dns_servers print("DNS Servers used for resolution:", get_active_dns_servers())
On Windows
- You can access system DNS settings via the Windows Registry using the built-in
winregmodule:
import winreg def get_windows_dns_servers(): dns_servers = [] reg_path = r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters' try: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path) as key: dns_data, _ = winreg.QueryValueEx(key, 'NameServer') dns_servers = dns_data.split() except FileNotFoundError: print("DNS server entry not found in registry") return dns_servers print("Windows DNS Servers:", get_windows_dns_servers())
2. 是否可以借助psutil或其他工具,获取类似Windows命令ipconfig /displaydns的输出结果?(不启动cmd进程)
Short answer: psutil doesn't directly expose DNS cache data—it's focused on process monitoring, system resources, and network connections, not DNS cache entries. But there are reliable ways to get this data without spawning a cmd process:
Option 1: Call Windows API via ctypes
You can interact directly with Windows system DLLs to query the DNS cache. Here's a functional (simplified) example (note: admin privileges may be required for full cache access):
import ctypes from ctypes import wintypes # Load Windows system DLLs dnsapi = ctypes.WinDLL('dnsapi.dll') kernel32 = ctypes.WinDLL('kernel32.dll') # Define the DNS cache entry structure (simplified version) class DNS_CACHE_ENTRY(ctypes.Structure): _fields_ = [ ("pNext", wintypes.LPVOID), ("recName", wintypes.LPWSTR), ("wType", wintypes.WORD), ("wDataLength", wintypes.WORD), ("dwFlags", wintypes.DWORD), ] # Set up function signatures for DNS API calls dnsapi.DnsEnumerateCacheEntry_W.argtypes = [ wintypes.LPWSTR, wintypes.DWORD, ctypes.POINTER(wintypes.LPVOID), wintypes.LPDWORD ] dnsapi.DnsEnumerateCacheEntry_W.restype = wintypes.DWORD def get_windows_dns_cache(): cache_entries = [] p_entry = wintypes.LPVOID() entry_count = wintypes.DWORD() # Enumerate all DNS cache entries result = dnsapi.DnsEnumerateCacheEntry_W(None, 0, ctypes.byref(p_entry), ctypes.byref(entry_count)) if result == 0: current_entry = p_entry for _ in range(entry_count.value): entry = ctypes.cast(current_entry, ctypes.POINTER(DNS_CACHE_ENTRY)).contents if entry.recName: cache_entries.append(entry.recName) current_entry = entry.pNext # Clean up allocated memory kernel32.LocalFree(p_entry) return cache_entries print("Windows DNS Cache Entries:\n", "\n".join(get_windows_dns_cache()))
You can expand the DNS_CACHE_ENTRY structure to fetch more details (like record type, TTL, or data) by referencing official Windows API docs.
Option 2: Use the pywin32 library
If you have the pywin32 package installed (a common Windows Python utility library), you can simplify this with the win32dns module:
import win32dns # Fetch full DNS cache data dns_cache = win32dns.DnsGetCacheDataTable() for entry in dns_cache: print(f"Domain: {entry.name}, Record Type: {entry.type}, TTL: {entry.ttl}")
This gives you structured, human-readable DNS cache data that matches the output of ipconfig /displaydns.
内容的提问来源于stack exchange,提问作者user1314011

