开发者

Get remote MAC address using Python and Linux

How do I get the MAC address of a r开发者_如何学Cemote 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

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


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


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(']', '')      


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.


If you just want to query the OS' arp cache, reasonably recent linux kernels support this:

import os, sys

host = sys.argv[1]

# ping is optional (sends a WHO_HAS request)
os.popen('ping -c 1 %s' % host)

# grep with a space at the end of IP address to make sure you get a single line
fields = os.popen('grep "%s " /proc/net/arp' % host).read().split()
if len(fields) == 6 and fields[3] != "00:00:00:00:00:00":
    print fields[3]
else:
    print 'no response from', host


Hi this is a quick fix to python3

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 :
    output = output.decode('ascii')
    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]))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜