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

Python本地网络IoT设备状态检测脚本优化:多MAC地址处理咨询

优化批量MAC地址检测的Python方案

嘿,这个场景我之前做家庭IoT设备监控的时候也碰到过!要从检测2个MAC扩展到20个,核心就是让代码变得更可维护、不用每次加新设备都改核心逻辑。下面给你几个实用的优化方案:

1. 用配置文件管理MAC列表(最推荐)

把所有目标MAC地址放到外部配置文件里,比如JSON或纯文本,这样后续新增设备只需要修改配置文件,完全不用碰代码逻辑。

举个JSON配置的例子,先创建一个target_macs.json文件:

{
    "mac_addresses": [
        "AA:BB:CC:DD:EE:FF",
        "11:22:33:44:55:66",
        "XX:YY:ZZ:AA:BB:CC"
        // 后续直接在这里加新MAC就行
    ]
}

然后修改你的Python脚本读取这个配置:

import json
import subprocess
import datetime

def load_target_macs(config_path):
    with open(config_path, 'r') as f:
        config = json.load(f)
    return [mac.lower() for mac in config['mac_addresses']]

def check_device_status():
    target_macs = load_target_macs('target_macs.json')
    # 执行arp -a命令并获取输出
    arp_output = subprocess.run(
        ['arp', '-a'], 
        capture_output=True, 
        text=True,
        encoding='utf-8'
    ).stdout
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # 遍历检测每个目标MAC
    for mac in target_macs:
        if mac in arp_output.lower():
            # 提取对应的IP(可选,让输出更直观)
            for line in arp_output.split('\n'):
                if mac in line.lower():
                    ip = line.split()[0]
                    print(f"✅ 设备在线 | IP: {ip} | MAC: {mac.upper()} | 检测时间: {current_time}")
                    break  # 找到就跳出,避免重复输出

if __name__ == "__main__":
    check_device_status()

这个方案的好处:

  • 完全解耦配置和代码,非开发人员也能轻松新增设备
  • 批量管理MAC地址更清晰,不容易出错

2. 用常量列表管理MAC(轻量方案)

如果不想用外部配置文件,直接在代码里定义一个常量列表,比写一堆if...elif判断干净太多:

import subprocess
import datetime

# 把所有目标MAC放在这里,新增直接加就行
TARGET_MACS = [
    "AA:BB:CC:DD:EE:FF".lower(),
    "11:22:33:44:55:66".lower(),
    "XX:YY:ZZ:AA:BB:CC".lower()
]

def check_device_status():
    arp_output = subprocess.run(['arp', '-a'], capture_output=True, text=True).stdout.lower()
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    for mac in TARGET_MACS:
        if mac in arp_output:
            # 提取IP逻辑同上
            for line in arp_output.split('\n'):
                if mac in line:
                    ip = line.split()[0]
                    print(f"✅ 设备在线 | IP: {ip} | MAC: {mac.upper()} | 检测时间: {current_time}")
                    break

if __name__ == "__main__":
    check_device_status()

3. 用Scapy优化ARP扫描(高效方案)

如果检测20个设备时觉得调用arp -a解析输出效率低,可以用scapy库直接发送ARP请求,结果更准确,解析也更灵活:

首先安装scapy:

pip install scapy

然后编写脚本:

from scapy.all import ARP, Ether, srp
import datetime

TARGET_MACS = [mac.lower() for mac in [
    "AA:BB:CC:DD:EE:FF",
    "11:22:33:44:55:66",
    # 新增MAC直接加在这里
]]
# 替换成你的本地网段,比如192.168.0.0/24
LOCAL_NETWORK = "192.168.1.0/24"

def check_device_status():
    # 构造ARP请求包
    arp_request = ARP(pdst=LOCAL_NETWORK)
    broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_packet = broadcast / arp_request

    # 发送请求并获取响应
    responses, _ = srp(arp_packet, timeout=2, verbose=0)
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # 整理在线设备的MAC和IP映射
    online_devices = {resp.hwsrc.lower(): resp.psrc for _, resp in responses}

    # 检查目标MAC是否在线
    for mac in TARGET_MACS:
        if mac in online_devices:
            print(f"✅ 设备在线 | IP: {online_devices[mac]} | MAC: {mac.upper()} | 检测时间: {current_time}")

if __name__ == "__main__":
    check_device_status()

这个方案的好处:

  • 主动扫描网络,比依赖系统ARP缓存更可靠(避免缓存过期漏检)
  • 直接获取结构化的响应结果,不用解析杂乱的命令输出
  • 可以自定义超时时间,批量检测效率更高

额外小技巧

  • 统一MAC地址的大小写:把所有MAC转成小写(或大写)再对比,避免因为大小写不匹配漏掉设备
  • 日志记录:把检测结果写到日志文件里,方便后续排查或统计
  • 定时检测:如果需要定期监控,可以用schedule库实现定时执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:29:01