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
相关推荐
quantdash_cc4 分钟前
历史数据断层与REST请求慢到崩溃?QuantDash高性能量化数据API终极解决方案
开发语言·python·缓存·php·量化·quantdash
熊野君8 分钟前
Prompt / RAG / 规则 / Skills —— 定位、协作与实现路线
开发语言·python
zhangphil34 分钟前
Python Web后端框架FastAPI vs Flask
python·ai·llm
ly76891 小时前
XML 从入门到实践:语法、命名空间、XPath、XSD 与 Java 安全解析
xml·java·python
winfredzhang1 小时前
用 Python + wxPython 造一个照片工具箱:PDF / 加密ZIP / MP4 / 归档,以及我在这过程中踩到的 4 个坑
python·pdf·zip·mp4·移动
卷无止境1 小时前
FastAPI 后台任务的边界,以及 Celery、Redis 与自建调度系统的选择
后端·python
卷无止境1 小时前
Linux + Docker + FastAPI 工程化实践指南
后端·python·fastapi
聪明蛋子哟11 小时前
Stagehand v3多语言SDK:Python/Go/Rust/Java下的浏览器自动化统一方案
python·golang·rust
今天AI了吗11 小时前
Python 基础语法(一):常量、变量、输入输出与运算符
开发语言·数据库·人工智能·python·sql·深度学习·机器学习