run custom script on USB connect in Linux

You can run custom scripts after you have connected a USB device to a Linux system. So you can then perform custom actions also only if a specific device was plugged in.

In modern Linux systems the udevd daemon is used to handle the devices. You can define rules for specific actions the udev should do.

First you have to gather some informations about your target device. You can use the command udevadm monitor to monitor udev events. Some useful commands are also:

udevadm monitor -pview all events with full properties
udevadm monitor -p -s blockview all events with full properties of block subsystem related events

If your device is already connected, you can also query the attributes of an existing device using (for example disk /dev/sdb): udevadm info -a -n /dev/sdb

Here you should extract some unique attributes of your device.

To run your custom script or command you have to create such a rules file, for example /etc/udev/rules.d/10-myusbstick.rules, defining the match rules for your extracted attributes and the wanted action.

SUBSYSTEM=="block", ACTION=="add", ENV{DEVTYPE}=="partition", ATTRS{idProduct}=="441a", ATTRS{idVendor}=="0815", ATTRS{serial}=="123697755110", ENV{UDISKS_AUTO}="0", ENV{UDISKS_IGNORE}="1", RUN += "/usr/local/sbin/"

You should check that for every event the attributes are matching, the script will be started. So if your rule is too wide, you will call your script multiple times. You can use udevadm monitor to monitor the events and you also can use a simple debug script to get a feeling about the handling:

echo "got event in pid: $$" >> /tmp/udevdebug.log
env >> /tmp/udevdebug-$$.log

The script will add an entry to the file /tmp/udevdebug.log with the own PID and will output the full environment, which contains all relevant variables from udevd, to an logfile.

One reply on “run custom script on USB connect in Linux”