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.
Python code
34 linesimport 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
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
- Parse the `lsusb` output to extract vendor/product names with a regex for more user‑friendly messages.
- 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
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
Keep learning
Related tutorials and quizzes for this topic.