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 cause a problem with normal usage.
Since our “connect” file will create the lock, the disconnect script needs to remove this. Therefore, the contents of our .../on_usb_out.sh
script are:
#!/bin/sh LOCK=/tmp/lockfile_for_plug_usb/bin/
rm -f /tmp/lockfile_for_plug_usb
On USB Connect
On recognition of a new universal serial bus, we already know that we want to create a LOCK file. Once this has been done, we can then run any scripts that we wish within reason (i.e. they need to be finite and without the possibility of breaking).
The .../on_usb_in.sh
script stores the current date in a log file and then runs a Python script that determines if there is a data storage device. If so, it transfers data to it: