home git github notes hackthebox search

Configuring USB notifications on Linux

If you want to receive a small notification as soon as a USB storage device is plugged in or plugged out, you're in the right place.

Your system detects a USB device upon connection or disconnection using a utility named udev. It allows for defining rules to perform specific tasks. Combined with notify-send, you can trigger desktop notifications instantly.

1. Creating a udev rule

Save the following as 99-usb-notify.rules under /etc/udev/rules.d/

ACTION=="add", SUBSYSTEM=="block", ENV{DEVTYPE}=="disk", RUN+="/usr/local/bin/usb-notify-add.sh '$env{ID_MODEL}'"
ACTION=="remove", SUBSYSTEM=="block", ENV{DEVTYPE}=="disk", RUN+="/usr/local/bin/usb-notify-rem.sh '$env{ID_MODEL}'"

2. Configuring the scripts

Save both scripts under /usr/local/bin/ and make them executable

usb-notify-add.sh
#!/bin/bash
DEVICE_NAME=${1:-"Unknown USB Device"}

USER_ID=$(id -u <your-username>)
export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$USER_ID/bus

sudo -u <your-username> DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS /usr/bin/notify-send "USB Connected" "Device: $DEVICE_NAME"
usb-notify-rem.sh
#!/bin/bash
DEVICE_NAME=${1:-"Unknown USB Device"}

USER_ID=$(id -u <your-username>)
export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$USER_ID/bus

sudo -u <your-username> DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS /usr/bin/notify-send "USB Disconnected" "Device: $DEVICE_NAME"

3. Reloading the udev rules

Once the files are saved, reload the udev configuration to apply the changes:

sudo udevadm control --reload-rules
sudo udevadm trigger

And just like that, you've setup USB notifications. Give it a try! Plug in a device and check if your system sends a notification with the device name.