如何使用Python提取网络ARP表中各设备的IP地址和物理地址
提取ARP表中IP和MAC地址的实现方法
arp -a命令的输出格式在不同操作系统中存在细微差异,用正则匹配标准格式的方案兼容性最强,无需适配不同系统的输出字段顺序:
import os import re # 预编译正则规则,分别匹配标准IPv4地址和兼容两种分隔符的MAC地址 ip_regex = re.compile(r'((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)') mac_regex = re.compile(r'([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})') arp_list = [] for line in os.popen('arp -a'): line = line.strip() # 跳过空行 if not line: continue ip_match = ip_regex.search(line) mac_match = mac_regex.search(line) # 仅保留同时匹配到IP和MAC的有效行 if ip_match and mac_match: arp_list.append({ "ip": ip_match.group(), "mac": mac_match.group() }) # 打印提取结果 for entry in arp_list: print(f"IP: {entry['ip']} 物理地址: {entry['mac']}")
如果你确定运行环境的ARP输出格式固定,也可以用字符串分割的简化方案,无需引入正则库,以类Unix系统为例:
import os arp_list = [] for line in os.popen('arp -a'): parts = line.strip().split() if len(parts) < 4: continue ip = parts[1].strip("()") mac = parts[3] # 简单校验MAC格式避免无效值 if 12 <= len(mac) <= 17: arp_list.append({"ip": ip, "mac": mac})
内容的提问来源于stack exchange,提问作者Aubin
相关产品推荐
相关产品推荐

