其中一種辦法是使用autofs,但是這種辦法是屬於比較被動的掛載。它是在有人訪問到某個資料匣時才會嘗試去檢查是否有可東西可以掛載在這個資料匣下。要更讓掛載更加自動化,可以改為使用udev的rules。
首先於 /dev/udev/rules.d 下建立檔案 99-usb-automount.rules:
KERNEL=="sd[a-z]1", RUN+="/usr/local/bin/usb_mount", ENV{REMOVE_CMD}="/usr/local/bin/usb_mount"
其中 /usr/local/bin/usb_mount 是一個shellscript,主要作用為依照udev所給的資訊進行掛載與卸載的動作。內容如下:
#!/bin/bash
# $Id$
#
# Script to automaticlly mount usb devices. This script is designed to work
# with udev
#
#commands used in the script
MOUNT="/bin/mount"
UMOUNT="/bin/umount -l"
MKDIR="/bin/mkdir -p"
RMDIR="/bin/rmdir"
#the root of where all auto mouted devices will be mounted to.
MOUNT_ROOT=/mnt
MNT_POINT=$MOUNT_ROOT/${DEVNAME##/dev/}
logger "running $0"
logger "ACTION=$ACTION ID_BUS=$ID_BUS DEVNAME=$DEVNAME
ID_FS_TYPE=$ID_FS_TYPE"
# check we are adding a usb device
if [ "$ID_BUS" != "usb" ]
then
logger "ignoring non usb device"
exit 0
fi
#check the action to process
case "$ACTION" in
add )
logger "mounting new device"
#create the directory we will mount to
$MKDIR "$MNT_POINT"
#
#mount the usb device with the following options
#
# ro - read only
# noexec - Do not allow direct execution of any binaries on the mounted file system
# nodev - Do not interpret character or block special devices on the file system
#
#$MOUNT -t $ID_FS_TYPE $DEVNAME $MNT_POINT -o ro,noexec,nodev
$MOUNT -t $ID_FS_TYPE $DEVNAME $MNT_POINT -o noexec,nodev
#check if mount suceeded
if [ $? -eq 0 ]
then
# sucess, we mounted ok.
logger "mounted $DEVNAME at $MNT_POINT"
else
# we failed to mount so remove the mount point
logger "failed to mount $DEVNAME at $MNT_POINT"
$RMDIR "$MNT_POINT"
fi
;;
remove )
logger "unmounting existing device"
# check if the device is really mounted
#if [ (grep -q "^$DEVNAME" /proc/mounts || grep -q "^$DEVNAME" /etc/mtab) ]
#then
# logger "$DEVNAME not mouted"
#endif
#unmount the device. We will refer using the mount point not the device name
#becase there is a posibility the device could be removed before we
#do the umount.
$UMOUNT "$MNT_POINT"
#remove the mount point
$RMDIR "$MNT_POINT"
logger "unmounted $DEVNAME and removed $MNT_POINT"
;;
* )
logger "ignoring unkown action"
;;
esac
這樣當USB儲存裝置一插入usb差槽後就可以看到裝置出現在 /mnt 下面。
原始文章來源在此 (想複製此script的人記得貼上後要檢查一下指令與註解有沒有因為html顯示的關係被斷行喔!)