How do I get the MAC address of a remote host on my LAN? I'm using Python and Linux.
You can try running command arp -a
Here is few links about Mac Address grabbing (not tested)
In Linux/Unix, arping,
http://www.ibm.com/developerworks/aix/library/au-pythocli/
In Windows, using IP Helper API through ctypes
Many years ago, I was tasked with gathering various machine info from all machines on a corporate campus. One desired piece of info was the MAC address, which is difficult to get on a network that spanned multiple subnets. At the time, I used the Windows built-in "nbtstat" command.
Today there is a Unix utility called "nbtscan" that provides similar info. If you do not wish to use an external tool, maybe there are NetBIOS libraries for python that could be used to gather the info for you?
you can use this on either win32 or linux
import subprocess
import sys
remotehost="192.168.0.122"
cmd="arp -a"
p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, errors = p.communicate()
if output is not None :
if sys.platform in ['linux','linux2']:
for i in output.split("\n"):
if remotehost in i:
for j in i.split():
if ":" in j:
print "%s--> %s" % (remotehost,j)
elif sys.platform in ['win32']:
item = output.split("\n")[-2]
if remotehost in item:
print "%s--> %s" %(remotehost, item.split()[1])
NB:arp entries goes off after a while, you need to "flood your network" eg ping, so that arp -a shows your remotehost.
arp entries might never be right, I tried to ping a host several times but arp -a would not give me it's mac/ethernet address. (No worry with the windows code from active state BTW)
The reliable way on Linux (and *nix) is to use arping or scappy (see http://en.wikipedia.org/wiki/Arping) and then parse the output. Here's the code I used. You have to be root or use sudo to run arping.
cmd = '/sbin/arping -c 1 ' + remotehost
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, errors = p.communicate()
if output is not None :
mac_addr = re.findall(r'(\[.*\])', output)[0].replace('[', '').replace(']', '')