基于subprocess
模块和正则表达式解析ipconfig /all
命令的输出,下面是一个兼容Windows英文版和中文版的Python脚本:
python
import subprocess
import re
# 输入或设定要查找的IP地址
ip_to_find = '192.168.100.10'
def find_adapter_by_ip(ip):
# 运行ipconfig命令并获取输出
output = subprocess.check_output(['ipconfig', '/all'], encoding='GBK')
# 定义匹配IP地址和适配器名称的正则表达式(考虑到中英文环境)
pattern_en = re.compile(r"IPv4 Address\. .*: (?P<ip_address>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*Physical Address. .*: .*(?P<adapter_name>.*)", re.DOTALL | re.IGNORECASE)
pattern_zh = re.compile(r"IPv4 地址\. .*: (?P<ip_address>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*物理地址. .*: .*(?P<adapter_name>.*)", re.DOTALL | re.IGNORECASE)
for line in output.splitlines():
match_en = pattern_en.match(line)
match_zh = pattern_zh.match(line)
if (match_en and match_en.group("ip_address") == ip) or (match_zh and match_zh.group("ip_address") == ip):
adapter_name = match_en.group("adapter_name") if match_en else match_zh.group("adapter_name")
return adapter_name.strip()
adapter_name = find_adapter_by_ip(ip_to_find)
if adapter_name:
print(f"找到IP地址为 {ip_to_find} 的网卡名称: {adapter_name}")
else:
print("没有找到IP地址为 {} 的网络接口。".format(ip_to_find))
# 阻塞程序直到用户按键(兼容不同系统的输入)
input("请按回车键退出...")
此脚本使用了两个正则表达式分别针对英文和中文环境下ipconfig
命令的输出格式。当在运行脚本时检测到与给定IP地址相匹配的行时,它会提取出对应的网卡名称。请注意,由于依赖于文本解析,这种方法可能不如直接使用psutil
库那样稳定和准确,尤其在不同Windows版本或定制版本下可能会有不同的输出格式。但在大部分标准Windows环境中应该能正常工作。