Automatically mounting USB drives
Automatically mount USB and other storages when plugged in.
397 Words, 3 Minutes
09 Mar 2024
Automatic mounting
It is possible to mount automatically USB and hard drives on OpenBSD.
Tested on OpenBSD 7.4.
Enabling hotplugd
The daemon hotplugd calls the scripts /etc/hotplug/attach and /etc/hotplug/detach when something is plugged in or unplugged. The following commands enable and start the service:
# rcctl enable hotplugd
# rcctl start hotplugd
Scripts attach & detach
The following shell scripts are a simple implementation of the attach and detach scripts.
The script attach should be copied to /etc/hotplug/attach. Each time a disk is plugged in, if it has a i partition, a directory is created under /tmp/drives, and the i partition is mounted inside. It works well with most disks, but it doesn't mount CD-ROM / ISO9660, which have to be mounted manually. Example of mounted directory: /tmp/drives/disk-sd3i.
Note: the directory and the files it contains can be read by any user, but they can be written only by members of the wheel group.
/etc/hotplug/attach
#!/bin/sh
# Only disks are automatically mounted
# See hotplugd(8)
if [ ! "$1" -eq "2" ];then
exit 0
fi
# Edit the variable below to mount the drives somewhere else
mountdest="/tmp/drives"
# Edit the variable below to change the prefix used in the mount directory
mountdirprefix="disk-"
disk="$2"
letter="i"
partition=$disk$letter
partitionpath=/dev/$partition
mountdir="$mountdest/$mountdirprefix$partition"
# Check if the disk has a i partition
/sbin/disklabel $partition | grep 'Device not configured'
partnotfound=$?
# The disk has no i partition, ignore it
if [ $partnotfound -eq 0 ];then
exit 0
fi
/bin/mkdir -p $mountdir
# Members of the wheel group can read & write
# Others can only read
/bin/chmod -R 775 $mountdir
/sbin/mount -o rw,nodev,noexec,nosuid $partitionpath $mountdir
The script detach should be copied to etc/hotplug/detach. When a disk is unplugged, the directory created by /attach is removed.
Note: the directory has to be unmounted manually before unplugging the drive. Example: umount /tmp/drives/disk-sd3i.
/etc/hotplug/detach
#!/bin/sh
# Only disks are automatically handled
# See hotplugd(8)
if [ ! "$1" -eq "2" ];then
exit 0
fi
# The two variable below must have the same values than in the attach script.
mountdest="/tmp/drives"
mountdirprefix="disk-"
disk="$2"
letter="i"
partition=${disk}$letter
partitionpath=/dev/$partition
mountdir="$mountdest/$mountdirprefix$partition"
# When the disk is unplugged, remove the (now empty) directory created
# in the attach script
if [ -d $mountdir ];then
rmdir $mountdir
fi