Obtain MAC Address from Devices using Python

Viewed 71871

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.

8 Answers

A simple solution using scapy, to scan the 192.168.0.0/24 subnet is as follows:

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))

General update for Python 3.7. Remark: the option -n for arp does not provide the arp list on windows systems as provided with certain answers for linux based systems. Use the option -a as stated in the answer here.

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))
Related