ubuntu实现自动挂载u盘
但是,有些设施可以在没有图形工具的情况下进行复制,并且在系统上占用的空间非常小。
例如,在我的设置中,我已经实现了USB自动挂载服务,而无需使用任何外部工具/服务,只有udev和systemd。
编写shell脚本
nano /usr/local/bin/usb-mount.sh
#!/bin/bashACTION=$1
DEVBASE=$2
DEVICE="/dev/${DEVBASE}"# See if this drive is already mounted
MOUNT_POINT=$(/bin/mount | /bin/grep ${DEVICE} | /usr/bin/awk '{ print $3 }')do_mount()
{if [[ -n ${MOUNT_POINT} ]]; then# Already mounted, exitexit 1fi# Get info for this drive: $ID_FS_LABEL, $ID_FS_UUID, and $ID_FS_TYPEeval $(/sbin/blkid -o udev ${DEVICE})# Figure out a mount point to useLABEL=${ID_FS_LABEL}if [[ -z "${LABEL}" ]]; thenLABEL=${DEVBASE}elif /bin/grep -q " /media/${LABEL} " /etc/mtab; then# Already in use, make a unique oneLABEL+="-${DEVBASE}"fiMOUNT_POINT="/media/${LABEL}"/bin/mkdir -p ${MOUNT_POINT}# Global mount optionsOPTS="rw,relatime"# File system type specific mount optionsif [[ ${ID_FS_TYPE} == "vfat" ]]; thenOPTS+=",users,gid=100,umask=000,shortname=mixed,utf8=1,flush"fiif ! /bin/mount -o ${OPTS} ${DEVICE} ${MOUNT_POINT}; then# Error during mount process: cleanup mountpoint/bin/rmdir ${MOUNT_POINT}exit 1fi}do_unmount()
{if [[ -n ${MOUNT_POINT} ]]; then/bin/umount -l ${DEVICE}fi# Delete all empty dirs in /media that aren't being used as mount points. for f in /media/* ; doif [[ -n $(/usr/bin/find "$f" -maxdepth 0 -type d -empty) ]]; thenif ! /bin/grep -q " $f " /etc/mtab; then/bin/rmdir "$f"fifidone
}
case "${ACTION}" inadd)do_mount;;remove)do_unmount;;
esac
chmod 777 /usr/local/bin/usb-mount.sh
编写服务
nano /etc/systemd/system/usb-mount@.service
[Unit]
Description=Mount USB Drive on %i[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/usr/local/bin/usb-mount.sh add %i
ExecStop=/usr/local/bin/usb-mount.sh remove %i
(我们使用“@”文件名语法,以便我们可以将设备名称作为参数传递)
编写udev规则
nano /etc/udev/rules.d/99-local.rules
KERNEL=="sd[a-z][0-9]", SUBSYSTEMS=="usb", ACTION=="add", RUN+="/bin/systemctl start usb-mount@%k.service"
KERNEL=="sd[a-z][0-9]", SUBSYSTEMS=="usb", ACTION=="remove", RUN+="/bin/systemctl stop usb-mount@%k.service"
KERNEL=="sd[a-z]", SUBSYSTEMS=="usb", ACTION=="add", RUN+="/bin/systemctl start usb-mount@%k.service"
KERNEL=="sd[a-z]", SUBSYSTEMS=="usb", ACTION=="remove", RUN+="/bin/systemctl stop usb-mount@%k.service"
更新配置
udevadm control --reload-rules
systemctl daemon-reload