Auto running commands when plugging in usb drives with udev in Linux

Auto running commands when plugging in usb drives with udev in Linux

My backup strategy for my machines at home can be effectively described as “scatty, but thorough“. Ā Or at least until I actually have a major crash and need to recover that important file that was outside of my normal documents, code repositories, and archived folders.

I am one of those sorts of people that has backups everywhere. Ā Folders stacked away with old dusty (and probably now useless) dvds. Ā Old hard drives filled with duplicates and archived files, stacked up in the back of cupboards and flung next to jam jars. Ā SD cards, USB keys, backups to other drives, backups to the machines on the other side of my flat, backups off-site. Ā Backups of backups backed up during the last backup.

So I decided to add one more with an external hard drive that I could plug in every now and then. Ā But backups aren’t really the point of this post.

Linux has a really powerful device manager called udev which detects when things are plugged into your machine (including hard drives), which you can write rules against, and have commands automagically executed. Ā This is really cool for my new hard drive, which can now automatically start backing up without regular cron jobs checking to see if it’s plugged in or not. Ā This is not the same as autorun files, it relies on that hard drive being plugged into that machine. Ā So don’t start crying about all the security risks with autorun, please.

Here’s how you do it.

[codesyntax lang=”bash”]udevadm info -a -p Ā $(udevadm info -q path -n /dev/sdc)[/codesyntax]

You’ll get a whole bunch of output from that, including (among a lot of other output) a line that might look a little like this:

[codesyntax lang=”bash”]ATTR{serial}==”312581808″[/codesyntax]

There are a lot more you can use as well, but this will identify your device.

Now create a new file insideĀ /etc/udev/rules.d/, such asĀ /etc/udev/rules.d/81-usb-drive.rules

[codesyntax lang=”bash”]KERNEL==”sd?1″, ATTRS{serial}==”312581808″, SYMLINK+=”backup-drive”, RUN+=”/bin/sh /home/user/scripts/backup-to-drive.sh”[/codesyntax]

Now every time you plug in that drive, that command is going to be executed (so include for example, the script that is going to run your backups). Ā Cool, eh?

I started thinking about other applications; syncing podcasts, ebooks and music are the obvious choices. Even as a crude simple method of executing commands on a box you don’t even usually login to. Ā Or you could use this technique to build yourself some poor man usb-based security. Ā Keep decryption keys on your thumb drive, and have it auto decrypt volumes on your machine when you plug in that particular drive.

Just don’t forget to keep a backup of the thumb drive, yeah?

Tags: , , , , ,

Leave a Reply?