使用Python从设备获取MAC地址 [英] Obtain MAC Address from Devices using Python

查看:1361
本文介绍了使用Python从设备获取MAC地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法(使用python)从本地网络上的设备获取layer II地址. Layer III地址是已知的.

I'm looking for a way (with python) to obtain the layer II address from a device on my local network. Layer III addresses are known.

目标是建立一个脚本,该脚本将定期轮询IP地址数据库,以确保mac地址没有更改,如果有更改,则将电子邮件警报发送给我自己.

The goal is to build a script that will poll a databases of IP addresses on regular intervals ensuring that the mac addresses have not changed and if they have, email alerts to myself.

推荐答案

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

To answer the question with Python depends on your platform. I don't have Windows handy, so the following solution works on the Linux box I wrote it on. A small change to the regular expression will make it work in OS X.

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

First, you must ping the target. That will place the target -- as long as it's within your netmask, which it sounds like in this situation it will be -- in your system's ARP cache. Observe:

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缓存检查代码,而您不想这样做:

Knowing that, you do a little subprocess magic -- otherwise you're writing ARP cache checking code yourself, and you don't want to do that:

>>> 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从设备获取MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆