Leaving an external USB hard drive or flash drive permanently mounted to your Linux server can pose a security risk and unnecessary wear on the physical drive itself. However, if the drive is used for automated tasks like nightly backups, manually mounting and unmounting it every day is tedious. By using a Linux daemon called autofs, you can configure your server to automatically mount the USB drive the exact moment a script attempts to access it, and automatically unmount it after a period of inactivity.
How to Install and Configure autofs
The autofs utility runs silently in the background, monitoring specific mount points. When a user or script requests a file from that location, autofs mounts the drive dynamically.
- Log into your Linux server via SSH.
- Update your package list and install the utility:
sudo apt update && sudo apt install autofs -y - Once installed, we must edit the master configuration file to tell
autofswhere to monitor. Open it using nano:sudo nano /etc/auto.master - Scroll to the bottom and add the following line. This tells
autofsto manage the/mnt/usbdirectory and look for specific instructions in a secondary file calledauto.usb, with a strict timeout of 60 seconds of inactivity:/mnt/usb /etc/auto.usb --timeout=60 - Save the file and exit (Press Ctrl+O, Enter, then Ctrl+X).
How to Map the Specific USB Drive
Now we must link the specific physical USB drive to that mount point using the drive’s unique UUID.
- Plug in your USB drive and run
sudo blkidto find its UUID (e.g.,UUID="1234-ABCD"). - Create the secondary map file we referenced earlier:
sudo nano /etc/auto.usb - Add the following line, replacing the UUID with your own, and defining the file system type (e.g., ext4, vfat, ntfs):
backup_drive -fstype=ext4,rw :/dev/disk/by-uuid/1234-ABCD - Save and exit the text editor.
- Restart the daemon to apply the changes:
sudo systemctl restart autofs
How the Automation Works
Your USB drive is now managed by autofs. If you run the df -h command, the drive will not appear as mounted. However, the moment you attempt to list the contents of the directory (ls /mnt/usb/backup_drive) or a backup script attempts to write a file there, autofs will intercept the command, instantly mount the drive, and process the request.
Because we set --timeout=60 in the master file, the daemon will start a timer the moment the read/write operation finishes. If 60 seconds pass without any further activity on the drive, autofs will automatically unmount it, safely disconnecting it from the operating system until it is needed again.