• 2011/12/12 - 17:28

    News

    The section "Nas/Router" has been added

Current page: Home > Tech

Udev autorun rules

Creating udev rules that run certain scripts when devices are getting pluged.

Step 1: Getting the required device information

Assuming the device is connected as an usb harddrive at /dev/sda1 you can use the udevadm command to get the information.

$ su
<ENTER ROOT PASSWORD>

# udevadm info -a -p /sys/block/sda

Udevadm info starts with the device specified by the devpath and then
walks up the chain of parent devices. It prints for every device
found, all possible attributes in the udev rules key format.
A rule to match, can be composed by the attributes of the device
and the attributes from one single parent device.

[...]

looking at parent device '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0':
    KERNELS=="0:0:0:0"
    SUBSYSTEMS=="scsi"
    DRIVERS=="sd"
    ATTRS{device_blocked}=="0"
    ATTRS{type}=="0"
    ATTRS{scsi_level}=="3"
    ATTRS{vendor}=="TOSHIBA "
    ATTRS{model}=="MK5055GSX       "
    ATTRS{rev}=="    "
    ATTRS{state}=="running"
    ATTRS{timeout}=="30"
    ATTRS{iocounterbits}=="32"
    ATTRS{iorequest_cnt}=="0x91cf"
    ATTRS{iodone_cnt}=="0x91cf"
    ATTRS{ioerr_cnt}=="0x0"
    ATTRS{modalias}=="scsi:t-0x00"
    ATTRS{evt_media_change}=="0"
    ATTRS{queue_depth}=="1"
    ATTRS{queue_type}=="none"
    ATTRS{max_sectors}=="240"

[...]

From this information you can take those parts identifying your device (in my case it was: vendor and model but a serial number works best).

Step 2: Configuring udev

The configuration files for udev are locatied at /etc/udev/rules.d and have a name like this: "<NUMBER>-<NAME>.rules". Here you have to create a new configuration file with the information obtained before.

# cat <<EOF> /etc/udev/rules.d/99-autorun.rules
KERNEL=="sd*", ACTION=="add", ATTRS{model}=="MK5055GSX       ", ATTRS{vendor}=="TOSHIBA", RUN+="/path/to/the/autorun/script.sh"
EOF

# udevadm control --reload-rules

Step 3: Writing the script

The script can do anything you want. Still, there might be problems with graphical applications called from the script as the environment variables might not be set correctly.

cat <<EOF>/path/to/the/autorun/script.sh
#! /bin/sh

# do something here
EOF

# chmod 750 /path/to/the/autorun/script.sh

Step 4: Final testing

Plug your device and check if the script is executed and working as expected.

last updated: May 4, 2020 17:36:28