Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get remote MAC address using Python and Linux

How do I get the MAC address of a remote host on my LAN? I'm using Python and Linux.

like image 759
myk_raniu Avatar asked Jan 06 '10 03:01

myk_raniu


3 Answers

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

http://code.activestate.com/recipes/347812/

like image 192
YOU Avatar answered Oct 19 '22 08:10

YOU


Use these commands:

arp -n <IP Address>|awk '/<ip address>/ {print $3}'

for example, if you want mac address of 192.168.10.1:

#arp -n 192.168.10.1|awk '/192.168.10.1/ {print $3}'
#00:0c:29:68:8f:a4
like image 39
hamSh Avatar answered Oct 19 '22 08:10

hamSh


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(']', '')      
like image 2
bsergean Avatar answered Oct 19 '22 07:10

bsergean