Linux: How to run python or bash script after inserting a pendrive


First, we need to create a file in /etc/udev/rules.d. In my case, it will be 99-custom-USB.rules.

nano /etc/udev/rules.d/99-custom-USB.rules

Next, we need to add content to this file:

ACTION==”add”, KERNEL==”sd[!0-9]|sr“, SUBSYSTEMS==”usb”, RUN+=”/usr/bin/sudo -u username /home/username/tests/script.sh %k”

Explanation:

ACTION==”add”:
This parameter specifies that the rule should be triggered when a new device is added.

KERNEL==”sd[!0-9]|sr”:
This parameter matches the kernel name of the device. It uses regular expressions to match either “sd” followed by a non-digit character or “sr”. This can match devices like /dev/sda or /dev/sr0.

SUBSYSTEMS==”usb”:
This parameter matches the subsystem of the device. In this case, it matches USB devices.

RUN+=”/usr/bin/sudo -u username /home/username/tests/script.sh %k”:
This parameter defines the action to be taken when the rule is triggered. It specifies a command to be run, which starts with executing the “/usr/bin/sudo” command as the “username” user, followed by the path to the script “/home/username/tests/script.sh”. The “%k” is a placeholder that will be replaced with the kernel name of the device that triggered the rule, like sda.

Now we only need to create bash (or python) script in path /home/username/tests/script.sh which will be triggered by this rule.

Leave a Reply

Your email address will not be published. Required fields are marked *