nfa*_*rar 19 python mac-address ip-address
我正在寻找一种方法(使用python)从本地网络上的设备获取第二层地址.第三层地址是已知的.
目标是构建一个脚本,定期轮询IP地址数据库,确保mac地址没有改变,如果有,则向我自己发送电子邮件警报.
Jed*_*ith 19
用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
Run Code Online (Sandbox Code Playgroud)
知道了,你做了一点子进程魔法 - 否则你自己编写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"
Run Code Online (Sandbox Code Playgroud)
此网站不久前也回答了类似的问题。正如该问题的问询者所选择的答案中提到的那样,Python没有内置的方法来执行此操作。您必须调用诸如arp获取ARP信息之类的系统命令,或者使用Scapy生成自己的数据包。
编辑:从他们的网站使用Scapy的示例:
这是另一个工具,它将持续监视计算机上的所有接口并打印它看到的所有ARP请求,甚至在监视模式下也可以显示来自Wi-Fi卡的802.11帧。请注意sniff()的store = 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)
Run Code Online (Sandbox Code Playgroud)
并非您要找的东西,但绝对是正确的。请享用!