nfarrar nfarrar - 1 year ago 253
Python Question

Obtain MAC Address from Devices using Python

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.

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.

Answer Source

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.

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
PING ( 56(84) bytes of data.
64 bytes from icmp_seq=1 ttl=64 time=1.25 ms

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

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
>>> IP = ""

>>> # 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 ="(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0]
>>> mac
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download