Home » Detecting USB devices being added or removed using Python

Detecting USB devices being added or removed using Python

In this article, we will look at a Python library that will allow you to monitor the USB devices connected to your system

This is a description of the library we will be using – USBMonitor

USBMonitor is a versatile cross-platform library that simplifies USB device monitoring for both Windows and Linux systems. It enables developers to effortlessly track device connections, disconnections, and access to all connected device attributes.

At its core, USBMonitor utilizes pyudev (for Linux environments) and WMI (for Windows environments), handling all the low-level intricacies and translating OS-specific information to ensure consistency across both systems.

So sure being on a Windows PC I could do the same with WMI but I also have a Linux setup – so as you can see the cross-platform support may be an advantage. The demo video in the link below actually shows a USB device being plugged into a Raspberry Pi


To install USBMonitor, simply run:

pip install usb-monitor


In the first example we will display all USB devices attached to the test system

List all devices

from usbmonitor import USBMonitor
from usbmonitor.attributes import ID_MODEL, ID_MODEL_ID, ID_VENDOR_ID

# Create the USBMonitor instance
monitor = USBMonitor()

# Get the current devices
devices_dict = monitor.get_available_devices()

# Print them
for device_id, device_info in devices_dict.items():
    print(f"{device_id} -- {device_info[ID_MODEL]} ({device_info[ID_MODEL_ID]} - {device_info[ID_VENDOR_ID]})")

When this is run I saw this in the repl window

This was actually a few of the devices

USB\VID_1462&PID_7C37\A02019050806 — USB Input Device (7c37 – 1462)
USB\VID_046D&PID_082D\19A752AF — USB Composite Device (082d – 046d)
USB\VID_045B&PID_0209\9&3884D9EE&0&1 — Generic USB Hub (0209 – 045b)
USB\VID_05E3&PID_0608\8&29C54EA8&0&6 — Generic USB Hub (0608 – 05e3)
USB\VID_045B&PID_0209\8&2EFE0359&0&5 — Generic USB Hub (0209 – 045b)
USB\VID_046D&PID_C534\9&B9DEF5F&0&3 — USB Composite Device (c534 – 046d)
USB\VID_045E&PID_028E\00000000 — Xbox 360 Controller for Windows (028e – 045e)

Now lets set up the monitoring example

USB monitoring example

This is the typical monitoring use case scenario, create callbacks for devices being connected and disconnected and then set up the monitoring daemon to monitor them.

from usbmonitor import USBMonitor

if __name__ == '__main__':
    # Test the USB monitor
    device_info_str = lambda \
        device_info: f"{device_info['ID_MODEL']} ({device_info['ID_MODEL_ID']} - {device_info['ID_VENDOR_ID']})"
    # Define the `on_connect` and `on_disconnect` callbacks
    on_connect = lambda device_id, device_info: print(f"Connected: {device_info_str(device_info=device_info)}")
    on_disconnect = lambda device_id, device_info: print(f"Disconnected: {device_info_str(device_info=device_info)}")

    #on_connect = lambda device_id, device_info: print(f"Device connected: {device_id} - {device_info}")
    #on_disconnect = lambda device_id, device_info: print(f"Device disconnected: {device_id} - {device_info}")
    usb_monitor = USBMonitor()
    usb_monitor.start_monitoring(on_connect=on_connect, on_disconnect=on_disconnect)

    _input = ''
    while _input != 'q':
        _input = input("Monitoring USB connections. Press 'q'+ Enter to quit")

To test this I ran the python example and plugged a USB flash disk into the PC and removed it, here is what I saw in the repl window

Monitoring USB connections. Press ‘q’+ Enter to quit
Connected: SanDisk Ultra USB Device (gendisk – gendisk)
Connected: USB Mass Storage Device (5581 – 0781)
Disconnected: SanDisk Ultra USB Device (gendisk – gendisk)
Disconnected: USB Mass Storage Device (5581 – 0781)

As you can see it detected the flash drive was inserted then removed.



You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More