Saturday, January 19, 2019

Automatically Mount USB Drive in Raspbian

This blog is mostly information for myself but maybe the powers of google will bless you with this search result. If you use Raspbian for only command line USB devices don't mount automatically.
Luckily the process to get it to work is pretty easy.
Unfortunately there are lots of documented processes that aren't very good. You should use a udev rule for this not any of the other funky junk.

You should be able to do most of this by installing the usbmount package (https://github.com/rbrito/usbmount) but it doesn't always work perfectly out of the box so I've been sticking to this solution because it has always worked for me.

The biggest piece is to use this automount rule from Axllent.org

Create a file /etc/udev/rules.d/11-media-by-label-auto-mount.rules that contains the following.

 KERNEL!="sd[a-z][0-9]", GOTO="media_by_label_auto_mount_end"   
 # Import FS infos   
 IMPORT{program}="/sbin/blkid -o udev -p %N"   
 # Get a label if present, otherwise specify one   
 ENV{ID_FS_LABEL}!="", ENV{dir_name}="%E{ID_FS_LABEL}"   
 ENV{ID_FS_LABEL}=="", ENV{dir_name}="usbhd-%k"   
 # Global mount options   
 ACTION=="add", ENV{mount_options}="relatime"   
 # Filesystem-specific mount options   
 ACTION=="add", ENV{ID_FS_TYPE}=="vfat|ntfs", ENV{mount_options}="$env{mount_options},utf8,gid=100,umask=002"   
 # Mount the device   
 ACTION=="add", RUN+="/bin/mkdir -p /media/%E{dir_name}", RUN+="/bin/mount -o $env{mount_options} /dev/%k /media/%E{dir_name}"   
 # Clean up after removal   
 ACTION=="remove", ENV{dir_name}!="", RUN+="/bin/umount -l /media/%E{dir_name}", RUN+="/bin/rmdir /media/%E{dir_name}"   
 # Exit   
 LABEL="media_by_label_auto_mount_end"  

Edit the udev config:  sudo nano /lib/systemd/system/systemd-udevd.service 
Comment out the last 7 lines and everything works normally. Comment below if you actually know what these do. Otherwise I'm not terribly worried.

 #KillMode=mixed  
 #WatchdogSec=3min  
 #TasksMax=infinity  
 #MountFlags=slave  
 #MemoryDenyWriteExecute=yes  
 #RestrictRealtime=yes  
 #RestrictAddressFamilies=AF_UNIX AF_NETLINK AF_INET AF_INET6  

Restart udev with the command:  sudo udevadm control --reload-rules
Restart the box with the command command:  sudo reboot

No comments:

Post a Comment