linuxudev

How can I create a udev rule to run a script when USB store is plugged in?


I need to run a Python or a shell script whenever a USB is plugged in.

So I need to create a udev rule for that.


Solution

  • You can add a udev rules file. For example, you can add the file /etc/udev/rules.d/99-local.rules:

    Its content can be:

    KERNEL=="sd*", SUBSYSTEMS=="block", ACTION=="add", RUN+="/bin/systemctl start usb-mount@%k.service"
    
    KERNEL=="sd*", SUBSYSTEMS=="block", ACTION=="remove", RUN+="/bin/systemctl stop usb-mount@%k.service"
    

    The previous is a udev rules file that starts and stops the systemd service usb-mount@.service by systemctl. By this service file you can start the desired Python or Bash script.

    A content example for the service file is the following:

    [Unit]
    Description=Mount USB Drive on %i
    
    [Service]
    Type=oneshot
    RemainAfterExit=true
    ExecStart=/usr/bin/usb-mount.sh add %i
    ExecStop=/usr/bin/usb-mount.sh remove %i
    

    Inside the unit file you can find the options ExecStart and ExecStop that start the Bash script /usr/bin/usb-mount.sh. The script accepts two arguments:

    1. add | remove
    2. the name of the USB device file (sda, sdb, sdb1, and so on).

    So usb-mount.sh is called when you insert (ACTION==add in the udev rule) or remove (ACTION==remove in the udev rule) a USB storage device.