Python如何过滤JSON数组中指定Intel网卡的MAC地址?
过滤指定网卡MAC地址的实现方法
现有代码的问题
- 判断条件误用赋值符号
=,且需求是网卡名称包含指定字符串,不是完全相等,应该用in关键字做包含判断 - 循环内固定取索引为0的网卡信息,无论匹配到哪个网卡,都只会输出第一个网卡的名称,逻辑错误
- 没有做两类网卡的分类筛选和存储逻辑
可直接运行的修正代码
import json response ='{"message_response":{"compdetailssummary":{"computer_summary":{"computer_name":"ABC","primary_owner":"Windows User","domain_name":"WORKGROUP"},"computer_network_adapter_summary":[{"dhcp_status":"Enabled","adapter_name":"[00000001] Fortinet Virtual Ethernet Adapter (NDIS 6.30)","mac_address":"00:00:0F:00:00:01","dhcp_server":"-","ip_address":"-","gateway":"-"},{"dhcp_status":"Enabled","adapter_name":"[00000004] Intel(R) Ethernet Connection I219-LM","mac_address":"00:00:0F:00:00:01","dhcp_server":"-","ip_address":"-","gateway":"-"},{"dhcp_status":"Enabled","adapter_name":"[00000005] Intel(R) Dual Band Wireless-AC 8260","mac_address":"00:00:0F:00:00:01","dhcp_server":"1.1.9.1","ip_address":"1.2.9.3","gateway":"1.1.8.1"},{"dhcp_status":"Enabled","adapter_name":"[00000007] Bluetooth Device (Personal Area Network)","mac_address":"00:00:0F:00:00:01","dhcp_server":"-","ip_address":"-","gateway":"-"},{"dhcp_status":"Disabled","adapter_name":"[00000002] PPPoP WAN Adapter","mac_address":"-","dhcp_server":"--","ip_address":"--","gateway":"--"},{"dhcp_status":"Enabled","adapter_name":"[00000003] Fortinet SSL VPN Virtual Ethernet Adapter","mac_address":"00:00:0F:00:00:01","dhcp_server":"--","ip_address":"--","gateway":"--"}]}}}' json_data = json.loads(response) # 提前提取公共字段,减少重复写长路径 computername = json_data['message_response']['compdetailssummary']['computer_summary']['computer_name'] all_adapters = json_data['message_response']['compdetailssummary']['computer_network_adapter_summary'] # 分别存储两类网卡的MAC地址,适配单设备多同类型网卡的场景 eth_mac = [] wifi_mac = [] for item in all_adapters: name = item["adapter_name"] mac = item["mac_address"] if "Intel(R) Ethernet" in name: eth_mac.append(mac) print(f"以太网适配器:{name},MAC:{mac}") elif "Intel(R) Dual Band Wireless" in name: wifi_mac.append(mac) print(f"WiFi适配器:{name},MAC:{mac}") # 输出最终汇总结果 print(f"\n设备名称:{computername}") print(f"全部Intel以太网MAC:{eth_mac}") print(f"全部Intel WiFi MAC:{wifi_mac}")
运行效果
用你提供的样例JSON运行后,会自动过滤掉虚拟网卡、蓝牙网卡等无关内容,输出匹配到的1个以太网和1个WiFi网卡的信息,即使返回的网卡数量超过12个也能正常筛选。
内容的提问来源于stack exchange,提问作者Imtiaz Ali
相关产品推荐
相关产品推荐

