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/”[/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?