Obtain MAC Address from Devices using Python

前端 未结 8 932
余生分开走
余生分开走 2020-11-30 03:34

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

相关标签:
8条回答
  • 2020-11-30 04:10

    There was a similar question answered not too long ago on this site. As mentioned in the answer chosen by the asker of that question, Python doesn't have a built-in way to do it. You must either call a system command such as arp to get ARP information, or generate your own packets using Scapy.

    Edit: An example using Scapy from their website:

    Here is another tool that will constantly monitor all interfaces on a machine and print all ARP request it sees, even on 802.11 frames from a Wi-Fi card in monitor mode. Note the store=0 parameter to sniff() to avoid storing all packets in memory for nothing.

    #! /usr/bin/env python
    from scapy import *
    
    def arp_monitor_callback(pkt):
        if ARP in pkt and pkt[ARP].op in (1,2): #who-has or is-at
            return pkt.sprintf("%ARP.hwsrc% %ARP.psrc%")
    
    sniff(prn=arp_monitor_callback, filter="arp", store=0)
    

    You could also do something similar to the verified answer. See https://scapy.readthedocs.io/en/latest/routing.html

    >>> mac = getmacbyip("10.0.0.1")
    >>> mac
    'f3:ae:5e:76:31:9b'
    

    This is fully cross platform.

    Not exactly what you're looking for, but definitely on the right track. Enjoy!

    0 讨论(0)
  • 2020-11-30 04:11

    for Unix based systems:

    #!/usr/bin/env python2.7
    
    import re
    import subprocess
    arp_out =subprocess.check_output(['arp','-lan'])
    
    re.findall(r"((\w{2,2}\:{0,1}){6})",arp_out)
    

    will return list of tuples with macs. scapy is an amazing tool , but seems to be overkill for this case

    0 讨论(0)
提交回复
热议问题