The issue with that is, for the system to automatically mount the encrypted device, the key for that device must be stored on the same system somewhere. So, if your system is stolen, the key could be compromised. If this is okay for you, then read on.
udev is the plug-and-play manager of Linux; anytime hardware is (dis)connected, it goes through
udev is responsible for putting it in the
/dev directory somewhere or doing whatever needs to be done to make it recognized by the rest of Linux. By digging into the depths of how
udev works, you'll find it's possible to run a script when a USB mass storage device is connected.
Basically you'll need to go to /etc/udev/rules.d. All files here are parsed by
udev when it (re)starts, and these files can be used to fire off scripts when certain devices are connected. Don't change anything you see here, but I added a
z60_usbmount.rules with the following contents:
KERNEL=="sd*", BUS=="usb", ACTION=="add", RUN+="/etc/local/usbmountcheck udev add $kernel $parent"
KERNEL=="sd*", ACTION=="remove", RUN+="/etc/local/usbmountcheck udev remove $kernel $parent"
Thus when any external drive is attached via usb, that usbmountcheck script will run, with all the information
udev gives up about the device.
usbmountcheck script is a bit complicated, because you want to uniquely identify the drive, and the
sdb, etc. name, the
$kernel name, won't do that. Here's the bit of logic I included in my script to do that:
# correlate volume name in /dev/disk/by-id with $KVOL, if we can
VNAME="`/bin/ls -l /dev/disk/by-id | /bin/grep $KVOL | /usr/bin/tr -s [[:space:]] ' ' | /usr/bin/cut -f 9 -d ' '`"
if [ "$?" != 0 ]; then
die "error in pipeline that tries to get volume name, return code $?"
At this point
$VNAME will have the device name as identified by USB. You can then test if it's a known encrypted volume, and script the appropriate commands to mount it. You'll also have to script an umount handler to automatically cleanup after a disconnect.
There's a lot of dangers in writing udev scripts because if they fail it could prevent udev from working and recognizing further hardware changes. Tread with caution.