Debian – How to automount usb drives in Linux (Debian)

automountingdebianusbusb-drive

With every new release the way to automount USB drives in Linux seems to change (fortunately I'm using Debian, so I'm only losing a few days on this every 2 years). We used to have usbmount, udisks, udisks2, udisks-glue, pmount, custom udev rules, and I'm probably forgetting many more. (A quick look shows that at least a thing named afuse seems to exist, but is not documented too well). None of these work anymore (for me at least).

What is the "current" way to automount USB drives in Debian? I used the following udev rule, but since updating from stretch to buster this stopped working:

SUBSYSTEM=="usb", DRIVERS=="usb-storage", ACTION=="add", \
RUN+="mkdir /media/usb%n; mount -o gid=plugdev,umask=002,fmask=111,users /dev/%k%n /media/usb%n"

Also: what is the stable solution to do this, that will reliably work even after updating to a new release, that I probably missed?

Best Answer

You can create a systemd.mount and systemd.automount unit files. Here is an example:

To mount /dev/sdb1 under /mnt/moutpoint , create a mnt-mountpoint.automount file:

sudo nano /etc/systemd/system/mnt-mountpoint.mount

Note: The name of the unit file should be dir-sub-dir.mount extracted from the mount point /dir/sub-dir (if you need to mount the device under /media the name will be media-mountpoint.mount)

Then paste the following lines:

[Unit]
Description=Mount sdb1

[Mount]
What=/dev/disk/by-uuid/UUID_here
Where=/mnt/mountpoint
Type=auto
Options=defaults

[Install]
WantedBy=multi-user.target

Use blkid to replace the UUID_here with the uuid of /dev/sdb1.

Create the mnt-mountpoint.automount file:

sudo nano /etc/systemd/system/mnt-mountpoint.automount

With the following lines:

[Unit]
Description=Automount usb

[Automount]
Where=/mnt/mountpoint

[Install]
WantedBy=multi-user.target

Attach your USB then enable and start the units:

sudo systemctl daemon-reload
sudo systemctl enable --now  mnt-mountpoint.mount mnt-mountpoint.automount
Related Question