I want to automatically mount a USB hard disk drive at a fixed mount point every time it gets plugged in. I also want to automatically unmount the device from the system when it’s unplugged.
With udev, this is easy.
First, attach the USB drive to the computer and find out its serial number:
$ /sbin/udevadm info -a -p $(/sbin/udevadm info -q path -n /dev/sdb)
(Here, I assume the drive is assigned /dev/sdb; check with dmesg if unsure.) This will spew out a lot of information, but it should be easy to track down. In my case, I see lines like this:
...
ATTRS{manufacturer}=="Western Digital"
ATTRS{product}=="My Passport 0730"
ATTRS{serial}=="57383"
...
Take a note of the serial number to identify the device.
Under /etc/udev/rules.d, create a file named like 80-usb-wd.rules, with the following content:
ACTION=="add", SUBSYSTEMS=="usb", ATTRS{serial}=="57583", SYMLINK+="wd%n"
ACTION=="add", SUBSYSTEMS=="usb", ATTRS{serial}=="57583", RUN+="/bin/mkdir /media/wd"
ACTION=="add", SUBSYSTEMS=="usb", ATTRS{serial}=="57583", RUN+="/bin/mount -t auto -o defaults /dev/wd1 /media/wd", OPTIONS="last_rule"
ACTION=="remove", SUBSYSTEMS=="usb", ATTRS{serial}=="57583", RUN+="/bin/umount /media/wd"
ACTION=="remove", SUBSYSTEMS=="usb", ATTRS{serial}=="57583", RUN+="/bin/rmdir /media/wd", OPTIONS="last_rule"
What these instructions do is two things. When the USB drive with the specific serial number is attached, udev creates device nodes like /dev/wd, /dev/wd0, /dev/wd1, …, the exact number of these nodes depending on how many partitions are in the drive. I only have one partition on this drive, and /dev/wd1 points to it. Then it creates a directory /media/wd, and the partition /dev/wd1 gets mounted to the node.
Unfortunately, the device is mounted as root, so in order to unmount the filesystem, I need to unmount as root:
$ sudo umount /media/wd
When the USB drive is removed from the system, it unmounts the partition and the /media/wd directory is deleted as well.
Restart udev and the change will be in effect:
$ sudo /etc/init.d/udev restart
This way I can expect the specific USB drive to be always mounted at /media/wd.
It works, but in reality is rather useless, since it mounts drive as root, so the drive will be read-only.
laur — It must be your setting. The system may mount but the access restrictions should depending on permissions on the filesystem. I read and write all the time.
It works, but I can’t create/modify any file/folder into /media/wd
I get: permission denied
darvein — I don’t have the same problem. You may need to set proper permissions for regular users (as root) before you write to the disk.
Hi, It works on Debian testing as well. I also tried it on a Ubuntu install (testing), and then my device spit out some other information. Hence the diffulculty of programming!
Thanks, Marco