Build a Python USB Device Monitor That Alerts You When a New Device Is Plugged In
USB attacks are old, simple and still effective. A malicious drive left in a car park, a “free” charger cable, a keyboard that is not really a keyboard — the moment it is plugged in, it can act. The defence starts with knowing the instant something new connects. This script watches your USB ports and tells you the moment a device appears.
Run it only on systems you own. This is a defensive monitoring tool for your own machines.
How it works
Linux exposes every connected USB device under /sys/bus/usb/devices/. Our script snapshots that list, then checks it every few seconds. When a device appears that was not there before, it logs the event with a timestamp and prints an alert. Nothing is installed, nothing runs as root, and the whole thing is under 60 lines.
The code
import os
import time
from datetime import datetime
USB_PATH = "/sys/bus/usb/devices"
def snapshot():
"""Return a dict of device id -> product name."""
devices = {}
for entry in os.listdir(USB_PATH):
product_file = os.path.join(USB_PATH, entry, "product")
if os.path.isfile(product_file):
with open(product_file) as f:
devices[entry] = f.read().strip()
return devices
def log_event(message):
stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{stamp}] {message}"
print(line)
with open("usb_events.log", "a") as f:
f.write(line + "\n")
def main():
known = snapshot()
print(f"Monitoring {len(known)} USB devices. Press Ctrl+C to stop.")
while True:
time.sleep(3)
current = snapshot()
for dev_id, name in current.items():
if dev_id not in known:
log_event(f"NEW DEVICE plugged in: {name} ({dev_id})")
for dev_id, name in known.items():
if dev_id not in current:
log_event(f"Device removed: {name} ({dev_id})")
known = current
if __name__ == "__main__":
main()
Save it as usb_monitor.py and run it with python3 usb_monitor.py. It prints every connection and removal, and appends the same lines to usb_events.log so you have a permanent record.
Making it actually useful
- Know your baseline. Run it once and note the devices that are always there — your keyboard, mouse, webcam. Anything outside that list is worth a look.
- Add a real alert. Printing is fine on your desk, but for a server, send the event somewhere you will see it: an email, a webhook, or a message to your phone. A log file nobody reads is not an alert.
- Whitelist, don’t just watch. On a shared machine, keep a list of approved device names. Alert loudly on anything not on the list, and treat unknown storage devices as hostile until proven otherwise.
- Pair it with policy. The script is the sensor; the rule is the defence. On any machine that matters, disable USB storage in the BIOS or with a udev rule, and let this monitor catch the exceptions.
The takeaway
Defence is mostly noticing. Attackers rely on the fact that nobody watches the small things — a new device, a new process, a new login at 3 a.m. A 60-line script that notices a USB stick the second it appears is a real layer of defence, and building it yourself teaches you more about how Linux sees hardware than any tutorial ever will.



Comments
Post a Comment