Detecting USB Device Insertion on Windows 10 using python

2024/4/15 1:14:08

I can't get the following code for Detecting USB Device Insertion to work on my Windows 10 (64 bit) computer with Python 3.7.

import win32serviceutil
import win32service
import win32event
import servicemanagerimport win32gui
import win32gui_struct
struct = win32gui_struct.struct
pywintypes = win32gui_struct.pywintypes
import win32conGUID_DEVINTERFACE_USB_DEVICE = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}"
DBT_DEVICEARRIVAL = 0x8000
DBT_DEVICEREMOVECOMPLETE = 0x8004import 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 Nonehdr_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_BROADCASTclass 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 handlefilter,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_DEVICEEVENTreturn 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. I start the script with the following command: python main.py start

  2. Then the following error messages appear in the command prompt:

Starting service DevEventHandler Error starting service: Access denied

  1. I then ran the script with administrator privileges: runas /user:administrator "python main.py start"

  2. Another error messages appear in the command prompt:

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

How can the 'The specified service does not exist as an installed service' error be fixed?

Answer

I tested with Python 3.8.2 x64.

  1. Install pywin32 (pip install pywin32)
  2. Install the current/last version (1.5) of the WMI module from https://github.com/tjguk/wmi (pip install -e git+https://github.com/tjguk/wmi.git#egg=wmi)
  3. run a script (test.py in my case), like:
import wmiraw_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. plug in a USB device. Output looks like:
(wmi-py) C:\Users\USER\Source\wmi-py>py test.pyinstance of Win32_USBHub
{Caption = "USB Composite Device";ConfigManagerErrorCode = 0;ConfigManagerUserConfig = FALSE;CreationClassName = "Win32_USBHub";Description = "USB Composite Device";
...

Many thanks to the WMI module author, and the Windows nerds' discussion here Detecting USB drive insertion and removal using windows service and c#

https://en.xdnf.cn/q/72986.html

Related Q&A

I get NotImplementedError when trying to do a prepared statement with mysql python connector

I want to use prepared statements to insert data into a MySQL DB (version 5.7) using python, but I keep getting a NotImplementedError. Im following the documentation here: https://dev.mysql.com/doc/con…

parsing transcript .srt files into readable text

I have a video transcript SRT file with lines in conventional SRT format. Heres an example:1 00:00:00,710 --> 00:00:03,220 Lorem ipsum dolor sit amet consectetur, adipisicing elit.2 00:00:03,220 --…

Sphinx Public API documentation

I have a large number of python file and I would like to generate public API documentation for my project. All the functions that are part of the api I have decorated with a decorator. for example:@api…

Debugging a scripting language like ruby

I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python.I am wondering how to do debugging. At present the steps I follow is, I c…

Running unittest Test Cases and Robot Framework Test Cases Together

Our group is evaluating Robot Test Framework for our QA group, not just for BDD, but also to possibly cover a lot of our regular functionality testing needs. It certainly is a compelling project.To wha…

numpy.ndarray enumeration over a proper subset of the dimensions?

(In this post, let np be shorthand for numpy.)Suppose a is a (n + k)‑dimensional np.ndarray object, for some integers n > 1 and k > 1. (IOW, n + k > 3 is the value of a.ndim). I w…

How can I work with a GLib.Array in Python?

I am writing a plugin for Rhythmbox, wherein a signal raised is passing in an object of type GArray. The documentation for GLib Arrays shows me a few methods I am interested in, but am unable to acces…

Categorical dtype changes after using melt

In answering this question, I found that after using melt on a pandas dataframe, a column that was previously an ordered Categorical dtype becomes an object. Is this intended behaviour?Note: not looki…

python apscheduler not consistent

Im running a scheduler using python apscheduler inside web.py framework. The function runserver is supposed to run everyday at 9 a.m but it is inconsistent. It runs most days but skips a day once in a …

Change timezone info for multiple datetime columns in pandas

Is there a easy way of converting all timestamp columns in a dataframe to local/any timezone? Not by doing it column by column?