Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

How to Monitor USB Device Connections in Python

A Python utility that monitors USB device connections and disconnections by comparing output of the lsusb command at regular intervals.

Medium Python 3.9+ Jun 28, 2026 Automation & scripting 2 views 0 copies

Python code

34 lines
Python 3.9+
import time
import subprocess
import os

def get_usb_devices():
    """Return list of currently connected USB devices (Linux)."""
    try:
        result = subprocess.run(['lsusb'], capture_output=True, text=True, check=True)
        return result.stdout.strip().split('\n')
    except (subprocess.CalledProcessError, FileNotFoundError):
        return []

def monitor_usb(interval=2):
    """Monitor USB connections and report changes."""
    previous = set(get_usb_devices())
    print("Monitoring USB devices... (Ctrl+C to stop)")
    try:
        while True:
            current = set(get_usb_devices())
            new_devices = current - previous
            removed_devices = previous - current
            if new_devices:
                for dev in new_devices:
                    print(f"[+] Connected: {dev}")
            if removed_devices:
                for dev in removed_devices:
                    print(f"[-] Disconnected: {dev}")
            previous = current
            time.sleep(interval)
    except KeyboardInterrupt:
        print("\nMonitoring stopped.")

if __name__ == "__main__":
    monitor_usb()

Output

stdout
Monitoring USB devices... (Ctrl+C to stop)
[+] Connected: Bus 002 Device 005: ID 0781:5567 SanDisk Corp. Cruzer Blade
[-] Disconnected: Bus 002 Device 004: ID 046d:c07e Logitech, Inc. G400s Optical Mouse

How it works

The script uses subprocess.run(['lsusb'], ...) to capture a snapshot of all currently connected USB devices on Linux. By converting the output to a set and comparing the current and previous snapshots, we efficiently detect which devices were added or removed. A simple time.sleep(interval) loop runs until the user presses Ctrl+C, which triggers a KeyboardInterrupt to stop gracefully. This approach relies only on the standard library and the lsusb command available on Linux systems, making it lightweight and dependency-free.

Common mistakes

  • Forgetting to handle the `KeyboardInterrupt` exception leads to ugly tracebacks on exit.
  • Assuming `lsusb` is available (it is Linux‑only) — the code does not work on Windows or macOS without porting.
  • Using a list instead of a set for comparison results in poor performance and incorrect diff semantics.
  • Not calling `strip()` on the captured stdout leaves trailing newlines, causing incorrect comparisons.

Variations

  1. Parse the `lsusb` output to extract vendor/product names with a regex for more user‑friendly messages.
  2. Use the `pyudev` library on Linux to listen for hotplug events instead of polling.

Real-world use cases

  • Triggering a backup script automatically when a USB storage device is plugged into a server.
  • Logging USB device insertion and removal for security auditing in a kiosk or lab environment.
  • Automatically mounting external drives and updating file system watchers when a USB stick is connected.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.