从使用Python的设备获取MAC地址
-
20-09-2019 - |
题
我在寻找一种方式(与Python)来获取我的本地网络上的设备的layer II
地址。 Layer III
地址是已知的。
我们的目标是建立一个脚本,将轮询数据库的IP的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没有内置的方式做到这一点。您必须调用系统命令,如arp
获取ARP信息,或使用生成自己的包 Scapy的
修改强>使用Scapy的从他们的网站的一个例子一个>:
下面是另一种工具,将 持续监控对所有接口 机和打印所有ARP请求它 看到,即使是在从802.11帧 Wi-Fi卡的监控模式。注意 商店= 0参数来嗅(),以避免 存储的所有数据包在内存中 什么都没有。
#! /usr/bin/env python
from scapy import *
def arp_monitor_callback(pkt):
if ARP in pkt and pkt[ARP].op in (1,2): #who-has or is-at
return pkt.sprintf("%ARP.hwsrc% %ARP.psrc%")
sniff(prn=arp_monitor_callback, filter="arp", store=0)
不是您寻找什么,但肯定在正确的轨道。享受!
听起来像是你想监控ARP欺骗者?在这种情况下,你需要的是 arpwatch ,在你身边每一个供应充足的Linux发行版提供。这里下载源: http://ee.lbl.gov/
用于基于Unix系统:
#!/usr/bin/env python2.7
import re
import subprocess
arp_out =subprocess.check_output(['arp','-lan'])
re.findall(r"((\w{2,2}\:{0,1}){6})",arp_out)
将返回用MACS元组的列表。 Scapy的是一个惊人的工具,但似乎是矫枉过正这种情况下
在Linux的sometimems你错过了命令行util的 “ARP”。甲碱yocto嵌入式Linux的例如环境图像。
没有“ARP”工具的另一种方式是读取和解析文件/ proc /净/ ARP:
root@raspberrypi:~# cat /proc/net/arp
IP address HW type Flags HW address Mask Device
192.168.1.1 0x1 0x2 xx:xx:xx:xx:xx:xx * wlan0
192.168.1.33 0x1 0x2 yy:yy:yy:yy:yy:yy * wlan0
更简单的方法中,如果在Linux:
print os.system('arp -n ' + str(remoteIP))
您将获得:
Address HWtype HWaddress Flags Mask Iface
192.168..... ether 9B:39:15:f2:45:51 C wlan0
使用Scapy的,一个简单的解决方案来扫描192.168.0.0/24的子网如下:
from scapy.all import *
ans,unans = arping("192.168.0.0/24", verbose=0)
for s,r in ans:
print("{} {}".format(r[Ether].src,s[ARP].pdst))
尝试使用这里找到netifaces。 netifaces
用于Python 3.7一般更新。注:该选项用于-n
arp
不能在Windows系统提供的ARP列表,提供了基于Linux系统的某些答案。这里的答案说使用选项-a
。
from subprocess import Popen, PIPE
pid = Popen(['arp', '-a', ip], stdout=PIPE, stderr=PIPE)
IP, MAC, var = ((pid.communicate()[0].decode('utf-8').split('Type\r\n'))[1]).split(' ')
IP = IP.strip(' ')
MAC = MAC.strip(' ')
if ip == IP:
print ('Remote Host : %s\n MAC : %s' % (IP, MAC))