5

I'm using Ubuntu 18.04 and I need to run a Bash script every time is plugged a new USB device (interdependently from the device type).

PS: I found other answers able to works for a specified USB device, but I need to works for ANY possible USB device.

2 Answers 2

6

Start systemd .service from an udev rule

udev monitor allows you to monitor kernel uevents and print the devpaths to the console, which can then be used by udevadm info -a --path='' to print all sysfs properties for all devices along the chain.

udevadm monitor --environment --udev lets you monitor environment variable set by udev events after the rule processing.

$ cat /etc/udev/rules.d/99-usb-autorun.rules
# Start USB autorun systemd .service
ENV{DEVTYPE}=="usb_device", \
TAG+="systemd", ENV{SYSTEMD_WANTS}="usb_autorun.service"

(dont forget to reload your rule udevadm control --reload && udevadm trigger).

...and /etc/systemd/system/usb_autorun.service:

[Unit]
Description=USB Autorun.

[Service]
Type=oneshot
ExecStart=/opt/bin/usb_autorun.sh
8
  • 1
    hope this doesnt match too much.
    – user986805
    Apr 15, 2020 at 21:27
  • I have to test it, but for the moment, thank you very much for the documentation ;)
    – maxwatt
    Apr 16, 2020 at 6:09
  • 1
    ENV{DEVTYPE}=="usb_device" was the most generic but still uniq I could find.
    – user986805
    Apr 16, 2020 at 14:12
  • 1
    does it run with systemctl start usb_autorun.service
    – user986805
    Apr 17, 2020 at 16:08
  • 1
    really strange, now all seems to works fine! Thanks so much!
    – maxwatt
    Apr 17, 2020 at 16:11
0

I developped a Python script that listens for specific devices and executes an action when the device is connected, eg:

pip install udev_monitor
udev_monitor.py --devices 0665:5161 --filters=usb --action /root/some_script.sh

The action will get as argument found device.

You can find the full sources here

There's also a systemd unit file and a configuration file example, so you can run a service monitoring a specific device.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .