linux系统基于pyudev的USB设备插拔检测

本文介绍了如何使用Python的pyudev模块来监控USB设备的添加和移除,通过创建Context和Monitor对象,过滤特定类型的设备,并捕获设备的详细信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pyudev

# 创建Context对象
context = pyudev.Context()

# 创建Monitor对象,监控事件
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by('block',device_type='partition')
# 开始监控
monitor.start()

# 遍历检测到的USB设备
for device in iter(monitor.poll, None):
    if device.action == 'add':
        # 打印设备信息
        print("USB设备已添加:")
        print(f"设备路径: {device.device_path}")
        print(f"设备节点: {device.device_node}")
        print(f"设备ID: {device.sys_name}")
        print(f"设备序列号: {device.get('ID_SERIAL_SHORT')}")
        print(f"设备制造商: {device.get('ID_VENDOR_ID')}")
        print(f"设备产品: {device.get('ID_MODEL_ID')}")
        print(f"设备描述: {device.get('ID_MODEL_ENC')}")

    elif device.action == 'remove':
        # 打印设备移除信息
        print("USB设备已移除:")
        print(f"设备路径: {device.device_path}")
        print(f"设备节点: {device.device_node}")
        print(f"设备ID: {device.sys_name}")
        print(f"设备序列号: {device.get('ID_SERIAL_SHORT')}")
        print(f"设备制造商: {device.get('ID_VENDOR_ID')}")
        print(f"设备产品: {device.get('ID_MODEL_ID')}")
        print(f"设备描述: {device.get('ID_MODEL_ENC')}")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值