您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Python从设备获取MAC地址

使用Python从设备获取MAC地址

用Python回答问题取决于您的平台。我没有Windows,因此以下解决方案可在我写过的Linux机器上使用。对正则表达式进行小的更改将使其在OS X中运行。

首先,您必须ping通目标。这将把目标(只要它在您的网络掩码之内,这听起来像是在这种情况下)就放置在系统的ARP缓存中。观察:

13:40 jsmith@undertow% ping 97.107.138.15
PING 97.107.138.15 (97.107.138.15) 56(84) bytes of data.
64 bytes from 97.107.138.15: icmp_seq=1 ttl=64 time=1.25 ms
^C

13:40 jsmith@undertow% arp -n 97.107.138.15
Address                  HWtype  HWaddress           Flags Mask            Iface
97.107.138.15            ether   fe:fd:61:6b:8a:0f   C                     eth0

知道这一点,您就做了一点子处理的魔术-否则您自己编写了ARP缓存检查代码,而您不想这样做:

>>> from subprocess import Popen, PIPE
>>> import re
>>> IP = "1.2.3.4"

>>> # do_ping(IP)
>>> # The time between ping and arp check must be small, as ARP may not cache long

>>> pid = Popen(["arp", "-n", IP], stdout=PIPE)
>>> s = pid.communicate()[0]
>>> mac = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0]
>>> mac
"fe:fd:61:6b:8a:0f"
python 2022/1/1 18:45:57 有315人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶