Member-only story
How to Run a Python Script on Insertion of a USB Device
A guide to trigger a data transfer or other process when inserting a USB in Linux
In our latest Raspberry Pi sensor project, we wanted to have a no-network approach to getting data automatically off it. The solution for this came through the running of a Python script on insertion of an “authorised” USB storage device.
In this article, I will explain how such a feat may be achieved.
The USB Rules
The simplest part lies in providing a set of rules on what to do upon insertion. These consist of a script for when we insert a USB and one for when we remove it:
ACTION=="add", SUBSYSTEM=="usb", PROGRAM="<full_path_here>/on_usb_in.sh"
ACTION=="remove", SUBSYSTEM=="usb", PROGRAM="<full_path_here>/on_usb_out.sh"
These two lines go into the etc/udev/rules.d
directory. For example:
nano /etc/udev/rules.d/custom_usb.rules
On USB Disconnect
As suggested by this post, we are able to use a LOCK file to show only when the device is plugged in and not run multiple instances of the code. This method has its drawbacks if we intend to plug multiple USBs at the same time, but this should seldom…