使用 python 检测 Windows 10 上的 USB 设备插入

2024-02-28

我无法获取以下代码检测USB设备插入 http://timgolden.me.uk/python/win32_how_do_i/detect-device-insertion.html在我的 Windows 10(64 位)计算机上使用 Python 3.7 工作。

import win32serviceutil
import win32service
import win32event
import servicemanager

import win32gui
import win32gui_struct
struct = win32gui_struct.struct
pywintypes = win32gui_struct.pywintypes
import win32con

GUID_DEVINTERFACE_USB_DEVICE = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}"
DBT_DEVICEARRIVAL = 0x8000
DBT_DEVICEREMOVECOMPLETE = 0x8004

import ctypes

#
# Cut-down clone of UnpackDEV_BROADCAST from win32gui_struct, to be
# used for monkey-patching said module with correct handling
# of the "name" param of DBT_DEVTYPE_DEVICEINTERFACE
#
def _UnpackDEV_BROADCAST (lparam):
  if lparam == 0: return None
  hdr_format = "iii"
  hdr_size = struct.calcsize (hdr_format)
  hdr_buf = win32gui.PyGetMemory (lparam, hdr_size)
  size, devtype, reserved = struct.unpack ("iii", hdr_buf)
  # Due to x64 alignment issues, we need to use the full format string over
  # the entire buffer.  ie, on x64:
  # calcsize('iiiP') != calcsize('iii')+calcsize('P')
  buf = win32gui.PyGetMemory (lparam, size)

  extra = {}
  if devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE:
    fmt = hdr_format + "16s"
    _, _, _, guid_bytes = struct.unpack (fmt, buf[:struct.calcsize(fmt)])
    extra['classguid'] = pywintypes.IID (guid_bytes, True)
    extra['name'] = ctypes.wstring_at (lparam + struct.calcsize(fmt))
  else:
    raise NotImplementedError("unknown device type %d" % (devtype,))
  return win32gui_struct.DEV_BROADCAST_INFO(devtype, **extra)
win32gui_struct.UnpackDEV_BROADCAST = _UnpackDEV_BROADCAST

class DeviceEventService (win32serviceutil.ServiceFramework):

  _svc_name_ = "DevEventHandler"
  _svc_display_name_ = "Device Event Handler"
  _svc_description_ = "Handle device notification events"

  def __init__(self, args):
    win32serviceutil.ServiceFramework.__init__ (self, args)
    self.hWaitStop = win32event.CreateEvent (None, 0, 0, None)
    #
    # Specify that we're interested in device interface
    # events for USB devices
    #
    filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE (
      GUID_DEVINTERFACE_USB_DEVICE
    )
    self.hDevNotify = win32gui.RegisterDeviceNotification (
      self.ssh, # copy of the service status handle
      filter,
      win32con.DEVICE_NOTIFY_SERVICE_HANDLE
    )

  #
  # Add to the list of controls already handled by the underlying
  # ServiceFramework class. We're only interested in device events
  #
  def GetAcceptedControls(self):
    rc = win32serviceutil.ServiceFramework.GetAcceptedControls (self)
    rc |= win32service.SERVICE_CONTROL_DEVICEEVENT
    return rc

  #
  # Handle non-standard service events (including our device broadcasts)
  # by logging to the Application event log
  #
  def SvcOtherEx(self, control, event_type, data):
    if control == win32service.SERVICE_CONTROL_DEVICEEVENT:
      info = win32gui_struct.UnpackDEV_BROADCAST(data)
      #
      # This is the key bit here where you'll presumably
      # do something other than log the event. Perhaps pulse
      # a named event or write to a secure pipe etc. etc.
      #
      if event_type == DBT_DEVICEARRIVAL:
        servicemanager.LogMsg (
          servicemanager.EVENTLOG_INFORMATION_TYPE,
          0xF000,
          ("Device %s arrived" % info.name, '')
        )
      elif event_type == DBT_DEVICEREMOVECOMPLETE:
        servicemanager.LogMsg (
          servicemanager.EVENTLOG_INFORMATION_TYPE,
          0xF000,
          ("Device %s removed" % info.name, '')
        )

  #
  # Standard stuff for stopping and running service; nothing
  # specific to device notifications
  #
  def SvcStop(self):
    self.ReportServiceStatus (win32service.SERVICE_STOP_PENDING)
    win32event.SetEvent (self.hWaitStop)

  def SvcDoRun(self):
    win32event.WaitForSingleObject (self.hWaitStop, win32event.INFINITE)
    servicemanager.LogMsg (
      servicemanager.EVENTLOG_INFORMATION_TYPE,
      servicemanager.PYS_SERVICE_STOPPED,
      (self._svc_name_, '')
    )

if __name__=='__main__':
  win32serviceutil.HandleCommandLine (DeviceEventService)
  1. 我使用以下命令启动脚本:python main.py start

  2. 然后命令提示符中出现以下错误信息:

Starting service DevEventHandler Error starting service: Access denied

  1. 然后我以管理员权限运行该脚本:runas /user:administrator "python main.py start"

  2. 命令提示符中出现另一个错误消息:

Starting service DevEventHandler Error starting service: The specified service does not exist as an installed service.

如何修复“指定的服务不作为已安装的服务存在”错误?


我使用 Python 3.8.2 x64 进行测试。

  1. 安装 pywin32 (pip install pywin32)
  2. 从以下位置安装 WMI 模块的当前/最新版本 (1.5)https://github.com/tjguk/wmi https://github.com/tjguk/wmi (pip install -e git+https://github.com/tjguk/wmi.git#egg=wmi)
  3. 运行脚本(test.py就我而言),例如:
import wmi

raw_wql = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA \'Win32_USBHub\'"
c = wmi.WMI ()
watcher = c.watch_for(raw_wql=raw_wql)
while 1:
  usb = watcher ()
  print(usb)
  1. 插入 USB 设备。输出看起来像:
(wmi-py) C:\Users\USER\Source\wmi-py>py test.py

instance of Win32_USBHub
{
        Caption = "USB Composite Device";
        ConfigManagerErrorCode = 0;
        ConfigManagerUserConfig = FALSE;
        CreationClassName = "Win32_USBHub";
        Description = "USB Composite Device";
...

非常感谢WMI模块作者,以及Windows nerds在这里的讨论使用 Windows 服务和 C# 检测 USB 驱动器的插入和移除 https://stackoverflow.com/questions/620144/detecting-usb-drive-insertion-and-removal-using-windows-service-and-c-sharp

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 python 检测 Windows 10 上的 USB 设备插入 的相关文章

随机推荐

  • 了解Android联系人的架构

    我正在开发一个 Android 应用程序 它需要知道何时添加 更新 删除联系人 所以我读了几篇文章 据我所知 每当联系人发生更改时 我们都可以通过内容观察者收到通知 但我们无法获取已添加 更新 删除的联系人 因此 我阅读了官方 API 并准
  • 来自 API 的 2 个并发请求数据混淆

    我使用 Nodejs 作为我的应用程序 API 的后端 但我意识到当有 2 个不同的用户不断请求同一个方法时 从 MySQL 请求返 回的数据有时可能会混淆 这是我的代码 router get v1 getList function req
  • 使用 Parcel 为浏览器构建 - 如何不输出 CommonJS 或 ES 模块

    我正在尝试编译一个我编写的库 以便可以将分布式文件放入script标记并在浏览器中运行 我正在尝试用 Parcel 2 来做到这一点 我觉得我已经很接近了 但每次我认为我在那里时都会出现一些新问题 关键是我想要它not捆绑外部依赖项 例如
  • 如果使用遗留库,如何避免 Java 中的未检查转换警告?

    我喜欢java中的泛型功能并且经常使用它 但如果我使用尚不支持泛型的库 我就会遇到问题 Servlet 就是一个例子 如果你使用ServletRequest getParameterMap 结果将是一个原始地图 但它只包括String作为钥
  • 在 R 3.1.1 (Windows) 中安装 rCharts 时出错

    是否有适用于 R 3 1 1 的 rCharts 版本 我尝试了2种方法 均失败 方法一 devtools install github ramnathv rCharts Downloading github repo ramnathv r
  • 是否可以在 Meta 刷新之前运行 JavaScript 代码

    一直以来 我们都在使用这个可靠的网站重定向 HTML JavaScript 代码
  • 如何在 Swift 中实现范围滑块

    我正在尝试实现范围滑块 并且使用了名为的自定义控件NMR范围滑块 https www cocoacontrols com controls nmrangeslider 但是当我使用它时 滑块根本不出现 难道也是因为它都是用 Objectiv
  • TestNG 跳过测试 - 为什么?

    我正在使用 testng 和 selenium 测试一个网络应用程序 测试主要包括打开应用程序的几个页面 并针对每个页面执行一些特定的活动 因此 我有一个执行 打开页面 测试的抽象基类 并定义了一个用作该测试的数据提供程序的抽象方法 然后有
  • 比较字符串时忽略希伯来语元音

    晚上好 我希望你能帮助我解决这个问题 因为我正在努力寻找解决方案 我有一个单词提供者 他给我元音希伯来语单词 例如 Vowelled 不元音 元音 不元音 与我的提供者不同 我的用户通常无法输入希伯来语元音 我也不应该希望他这样做 用户故事
  • Hill Cipher算法中如何计算逆密钥矩阵?

    我发现很难理解希尔密码算法中矩阵逆的计算方式 我知道这一切都是通过模算术完成的 但不知何故 事情并没有加起来 我真的很感激一个简单的解释 考虑以下希尔密码密钥矩阵 5 8 17 3 请使用上面的矩阵进行说明 你必须学习线性同余定理 http
  • Boost ASIO 和 co_await- 与任何第三方回调一起使用吗?

    一个简单的函数 awaitable
  • 仅在 Android 8.0 及更高版本上资源和布局方向渲染不正确

    我有一个多语言应用程序 主要语言为英语 次要语言为阿拉伯语 我正在打电话setLocale in the onCreate 每一个的Activity在我的应用程序中 public static void setLocale Locale l
  • 从桌面应用程序与 Silverlight 4 LocalMessageReceiver 通信

    我正在为 Silverlight 4 OOB 应用程序开发一个小助手应用程序 安装它可以稍微增强 SL 的功能 改进剪贴板支持 全局热键等 我知道 Silverlight 的本地消息 API 基于 ALPC 这是一个相当未记录的 Windo
  • 方法分配和对象

    我有一个 python 问题 我想将一个方法分配给另一个类的对象 但在这个方法中使用它自己的属性 由于我的项目中有许多具有不同使用方法的容器 不在该示例中 因此我不想使用继承 这将迫使我为每个实例创建一个自定义类 class contain
  • 手动写入后无法使用javascript更新textarea

    我正在编写一个在线应用程序 将一些文本保存到数据库中 大约有 5 个 textarea 和 5 个 input type text 我还实施了搜索以轻松查找和编辑数据库条目 将显示一个新的选择窗口 使用原型和 ajax 当单击其任何条目时
  • 使用 sqlite 进行 Node.js 护照身份验证

    它可以使用node js 护照和sqlite 数据库与会话吗 所有示例仅使用 mongoDb 我想收集 sqlite 中的所有数据 下面是一个使用示例护照本地 https github com jaredhanson passport lo
  • 使用 Jackson 反序列化枚举

    我正在尝试使用 Jackson 2 5 4 反序列化枚举 但失败了 而且我不太明白我的情况 我的输入字符串是驼峰式大小写 我想简单地映射到标准枚举约定 JsonFormat shape JsonFormat Shape STRING pub
  • JBoss AS 7 中的 hibernate 是否需要 c3p0 连接池

    我的项目正处于开始阶段 我在休眠方面遇到了一个大问题 我正在使用 hibernate 4 1 8 Final 和 c3p0 0 9 1 2 我有以下实体类 javax persistence Entity Table name CUSTOM
  • 在 Android 应用程序中提交带有 POST 数据的表单

    我已经在网上搜索一种方法来做到这一点大约一周了 但我似乎无法弄清楚 我正在尝试实现一个应用程序 我的大学可以使用它来允许用户轻松登录校园内的各种服务 目前的工作方式是他们进入在线门户 选择他们想要的服务 填写他们的用户名和密码 然后单击登录
  • 使用 python 检测 Windows 10 上的 USB 设备插入

    我无法获取以下代码检测USB设备插入 http timgolden me uk python win32 how do i detect device insertion html在我的 Windows 10 64 位 计算机上使用 Pyt