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
相关推荐
曲幽2 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程7 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪7 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook7 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田20 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python