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

使用python检测Windows 10上的USB设备插入,python,windows-10,usb,Python,Windows 10,Usb,我无法在使用Python3.7的Windows 10 64位计算机上获得以下代码 import win32serviceutil import win32service import win32event import servicemanager import win32gui import win32gui_struct struct = win32gui_struct.struct pywintypes = win32gui_struct.pywintypes import win32c

我无法在使用Python3.7的Windows 10 64位计算机上获得以下代码

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)
我使用以下命令启动脚本:python main.py start

然后,以下错误消息将显示在命令提示中:

正在启动服务deventhandler 启动服务时出错:访问被拒绝

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

命令提示中将显示另一条错误消息:

正在启动服务deventhandler 启动服务时出错:指定的服务不作为已安装的服务存在


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

我使用Python 3.8.2 x64进行了测试

安装pywin32 pip安装pywin32 从pip Install-e git安装WMI模块的当前/最新版本1.5+https://github.com/tjguk/wmi.gitegg=wmi 在我的例子中运行脚本test.py,如: 导入wmi raw_wql=从2内的_InstanceCreationEvent中选择*,其中TargetInstance为ISA“Win32_USBHub” c=wmi.wmi watcher=c.watch\u forraw\u wql=raw\u wql 而1: usb=观察者 printusb 插入USB设备。输出如下所示:
非常感谢WMI模块的作者,以及Windows nerds在这里的讨论

我尝试使用debug参数运行脚本,并出现一条消息说服务未安装。 试着先打字

python main.py安装

然后

python main.py start


这似乎不能解决您的问题,但应该是相关的:@AMC与此同时,我尝试了几乎所有相关的技巧和技巧,但在Python中启动Windows服务仍然不起作用。有人发布了关于此代码的帖子:@zer02我已经知道这篇帖子。看我的评论,你试过了吗?Works for mepython main.py安装会导致以下错误消息:安装服务DevEventHandler和错误安装服务:拒绝访问5是的,我已更改步骤3中的命令,请参见上文。不幸的是,出现一条消息,其中包含一条消息:python main.py安装尝试以用户DESKTOP-LL3RM2P\administrator身份启动,然后脚本终止。启动脚本后出现以下错误消息:1:回溯最近的调用上次:2:文件wmi-usb-detector.py,第5行,在3:watcher=c.watch\u forraw\u wql=raw\u wql 4:c:\Program Files\Python38\lib\site packages\wmi.py第1103行中,在watch\u for 5:wmi\u class=getattr self中,class\u name 6:TypeError:getattr:属性名称必须为string@Atalanttore您正在使用WMI模块版本1.4.9—pip附带的版本。具体版本很重要,你说得对。它是1.4.9版。从GitHub安装1.5.0版解决了此问题。同时感谢您更新您的说明。
(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";
...