Wouldn't it be nice if your USB sticks auto-mounted somewhere nice and easy on your Linux home media server, so you could play external media, perhaps controlled via VLC Remote from your phone, as soon as you plugged it in?  Here's how you do it.

SSH to your server and become root.  Go to /etc/udev/rules.d and create a file 80-usbmount.rules.

Put this in the file:

SUBSYSTEM=="block", ACTION=="add", ENV{ID_USB_DRIVER}=="usb-storage", ENV{DEVTYPE}=="partition", RUN+="/usr/local/sbin/usbPlug 'add' $env{DEVNAME}"
SUBSYSTEM=="block", ACTION=="remove", ENV{ID_USB_DRIVER}=="usb-storage", ENV{DEVTYPE}=="partition", RUN+="/usr/local/sbin/usbPlug 'remove' $env{DEVNAME}"

Restart udev: 

service udev restart

So now when a device is inserted in the "block" device subsystem, using the "usb-storage" driver, and it is a "partition", the /usr/local/sbin/usbPlug script is called to work some magic. 

You can get a full list of device attributes using the usbadm command:

udevadm info --query=all --name=/dev/sdc1

Any output line starting "E:" is a device property value you can test with "ENV{key}".

It will run the script with "add" or "remove" as a command and the full device path.  So, now we need a script which can mount this device in a known, easy location.  Save the following as /usr/local/sbin/usbPlug and "chmod 700 /usr/local/sbin/usbPlug" to make it executable:

#!/bin/bash
set -e

# Called by udev when a usb disk is plugged in.
# Tries to mount it in a known place.

args=$*
logger "usbPlug got: $args"

mpath="/mnt/bulk/media/video/"
mbase="usb"

if [ "$1" = "remove" ]; then
 mpoint=$(mount | grep $2 | cut -d' ' -f 3)
 logger "Unmounting $mpoint..."
 umount $mpoint || /bin/true;
 if [ -z "$(ls $mpoint)" ]; then rmdir $mpoint || /bin/true; fi;
 exit 0;
fi

for(( dnum=1; dnum<5; dnum++ )); do
 mpoint="$mpath$mbase$dnum"
 if [ -d $mpoint ]; then
  if [ ! -z $(ls $mpoint) ]; then
    # Dir exists and not empty - ignore
    continue;
  fi
 else
    mkdir $mpoint || /bin/true;
 fi

 # It exists and was empty or was just created...
 logger "Mounting $2 on $mpoint..."
 mount $2 $mpoint || /bin/true;
 break;
done;

So what does this do?  If it receives a "remove" command and a device, it finds out the mount path of it, unmounts it and (if empty) removes the directory/mount point.

Likewise, if it receives an "add" command and a device, it tries to create a directory and mount it.  The directory will be named usb{1,2,3...}, depending on what is available to use.  Its path is in the home of my media, so it is easy to find from the remote.

Enjoy.


...Click for More
Article
Auto Mount
hotplug
IT
Linux
Media Server
NAS
udev
USB