I am trying to get a script to run whenever ANY USB flash drive (not just a specific one) is plugged in to the system and I have been pulling my hair out for about 2 weeks now on and off trying to figure it out. Can anybody help me? (running Ubuntu if that helps).
I need to be able to pass the drive serial number and the devpath (/dev/sd**) at bear minimum.
First you need your rule to detect usb storage devices
/etc/udev/rules.d/10-usbmount.rules:
KERNEL=="sd*[!0-9]|sr*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/usr/bin/usbdevinserted"
This runs our custom executable shell script /usr/bin/usbdevinserted
:
#!/bin/bash
set 2>&1 >> /tmp/usbdevinfo
This sample script dumps the environment variables which you will need to know which device was found, eg:
DEVLINKS='/dev/disk/by-id/usb-Generic_USB_Flash_Disk-0:0 /dev/disk/by-path/pci-0000:00:13.2-usb-0:2:1.0-scsi-0:0:0:0'
DEVNAME=/dev/sdk
DEVPATH=/devices/pci0000:00/0000:00:13.2/usb2/2-2/2-2:1.0/host29/target29:0:0/29:0:0:0/block/sdk
DEVTYPE=disk
ID_BUS=usb
ID_FS_TYPE=
ID_INSTANCE=0:0
ID_MODEL=USB_Flash_Disk
ID_MODEL_ENC='USB\x20Flash\x20Disk\x20\x20'
ID_MODEL_ID=9380
ID_PART_TABLE_TYPE=dos
ID_PART_TABLE_UUID=61d1df0b
ID_PATH=pci-0000:00:13.2-usb-0:2:1.0-scsi-0:0:0:0
ID_PATH_TAG=pci-0000_00_13_2-usb-0_2_1_0-scsi-0_0_0_0
ID_REVISION=7.76
ID_SERIAL=Generic_USB_Flash_Disk-0:0
ID_TYPE=disk
ID_USB_DRIVER=usb-storage
ID_USB_INTERFACES=:080650:
ID_USB_INTERFACE_NUM=00
ID_VENDOR=Generic
ID_VENDOR_ENC='Generic\x20'
ID_VENDOR_ID=058f
MAJOR=8
MINOR=160
SUBSYSTEM=block