I have a USB key that contains my keepass2 password database and I’d like to perform some actions when it is plugged into my computer, namely:
- Auto-mount it to some specific location
- When the mounting is done properly, launching keepass2 on the password database file
Simple tasks I guess, but I can’t find how to do that.
I’m using Ubuntu 12.10, and it auto-mounts the device as a “media usb-key” and tries to open the images on it (even though there are none).
What is the best way to do that and to disable the ubuntu auto-mounting (so it doesn’t conflict) ?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
When a new device appears, udev is notified. It normally creates a device file under /dev based on built-in rules¹. You can override these rules to change the device file location or run an arbitrary program. Here is a sample such udev rule:
KERNEL=="sd*", ATTRS{vendor}=="Yoyodine", ATTRS{serial}=="123456789", NAME="keepass/s%n", RUN+="/usr/local/sbin/keepass-drive-inserted /dev/%k%n"
The NAME= directive changes the location of the device file, I included it for illustration purposes but it is probably not useful for your use case. The ATTRS rules identify the device; run udevinfo -a -n /dev/sdz when the drive is available as /dev/sdz to see what attributes it has. Beware that you can only use ATTRS rules from a single section of the udevinfo input (in addition, you can use ATTR rules from the initial section). See Understand output of `udevadm info -a -n /dev/sdb` for more background. This rule goes into a file called something like /etc/udev/rules.d/local-storage-keypass.rules.
Put the commands you want to run in the script given in the RUN directive. Something like:
#!/bin/sh
set -e
if [ -d /media/keypass-drive ]; then
[ "$(df -P /media/keypass-drive | awk 'NR==2 {print $1}')" = "$(df -P /media | awk 'NR==2 {print $1}')" ]
else
mkdir /media/keypass-drive
fi
mount "$1" /media/keypass-drive
su ereon -c 'keypass2' &
If you’re having trouble running a GUI program from a script triggered from udev, see Can I launch a graphical program on another user’s desktop as root?
¹ Not on modern systems where /dev is on udevtmpfs.
Method 2
The best way of doing this would be writing your own udev rule(s) for this device. Unfortunately I can’t give any tips on how to do this as I’ve never done so. So unless someone else has a more detailed answer, google for ‘udev rules’ and look in /lib/udev for examples. Your custom udev rules should go in /etc/udev/rules.d
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0