python获取目标主机的MAC地址

下载插件:WinPcap · Download

下载后直接安装(虽然已停止更新,但还能正常使用)

 

 python代码:安装 scapy

from scapy.all import Ether, ARP, srp


def get_mac_address(ip):
    # 创建一个ARP请求数据包
    arp = Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(op=1, pdst=ip)

    # 发送ARP请求并接收响应数据包
    result, _ = srp(arp, timeout=2, verbose=False)

    # 从响应数据包中获取目标主机的MAC地址
    if result:
        return result[0][1][Ether].src
    else:
        return None


# 示例用法
target_ip = "192.168.0.1"
mac_address = get_mac_address(target_ip)

if mac_address:
    print(f"目标主机 {target_ip} 的MAC地址为:{mac_address}")
else:
    print(f"无法获取目标主机 {target_ip} 的MAC地址")

会有两个异常提示:【不影响运行】

1、在 'all.py' 中找不到引用 'Ether

2、在 'all.py' 中找不到引用 'ARP' 

猜你喜欢

转载自blog.csdn.net/qq_41579327/article/details/131399159