python之使用scapy扫描本机局域网主机,输出IP/MAC表

安装scapy库

python 复制代码
pip install scapy -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple

扫描本机局域网的所有主机,输出IP/MAC对于表

python 复制代码
# -*- coding: UTF-8 -*-
import netifaces
from scapy.all import srp
from scapy.layers.l2 import ARP, Ether
import ipaddress


def get_local_network():
    """获取本机IP段/掩码"""
    ip_mask = []
    for iface in netifaces.interfaces():
        addrs = netifaces.ifaddresses(iface)
        if netifaces.AF_INET in addrs:
            for addr_info in addrs[netifaces.AF_INET]:
                if 'addr' in addr_info and 'netmask' in addr_info:
                    ip = addr_info['addr']
                    mask = addr_info['netmask']
                    if ip != '127.0.0.1':
                        network = ipaddress.IPv4Network(f"{ip}/{mask}", strict=False)
                        netmask = sum(bin(int(x)).count('1') for x in mask.split('.'))
                        ip_mask.append(f"{network.network_address}/{netmask}")

    return ip_mask


def scan_network(ip_range):
    """
    扫描指定 IP 范围内的主机,获取 IP 和 MAC 地址的对应关系
    :param ip_range: IP 范围,例如 "192.168.0.0/24"
    :return: IP/MAC 对应表
    """
    # ARP 请求包
    arp_request = ARP(pdst=ip_range)
    # 广播帧
    ether_frame = Ether(dst="ff:ff:ff:ff:ff:ff")
    # 数据包
    packet = ether_frame / arp_request

    # 发送并接收响应
    result = srp(packet, timeout=3, verbose=0, filter="arp")[0]

    # 解析结果
    ip_mac_table = []
    for sent, received in result:
        ip = received.psrc
        mac = received.hwsrc
        ip_mac_table.append((ip, mac))

    return ip_mac_table


def print_ip_mac_table(ip_mac_table):
    """
    打印 IP/MAC 对应表
    :param ip_mac_table: IP/MAC 对应表
    """
    print("IP/MAC 对应表:")
    print("-" * 35)
    print(f"{'IP':<15}{'MAC':<17}")
    print("-" * 35)
    for ip, mac in ip_mac_table:
        print(f"{ip:<15}{mac:<17}")
    print("-" * 35)


if __name__ == "__main__":
    ip_mac_table_result = []

    for ip_range in get_local_network():
        print(f"开始扫描 {ip_range} ...")
        ip_mac_table_result += scan_network(ip_range)

    print_ip_mac_table(ip_mac_table_result)

输出

python 复制代码
开始扫描 192.168.0.0/24 ...
IP Address       MAC Address         
--------------------------------------
192.168.0.113    4c:5f:70:6d:db:ca
相关推荐
曲幽1 小时前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户556918817532 小时前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维
兵慌码乱16 小时前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei19 小时前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi001 天前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn1 天前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵2 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup112 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill