Linux自动挂载U盘

0

安装驱动

yum install ntfs-3g
yum install fuse-exfat
yum install exfat-utils

添加配置

vim /etc/udev/rules.d/auto-mount.rules

#### USB
KERNEL=="sd[a-z]", SUBSYSTEM=="block", ACTION=="add", RUN+="/data/usb/auto-mount.sh %k /mnt/usb"
KERNEL=="sd[a-z]", SUBSYSTEM=="block", ACTION=="remove", RUN+="/data/usb/auto-mount.sh %k /mnt/usb"
KERNEL=="sd[a-z][0-9]", SUBSYSTEM=="block", ACTION=="add", RUN+="/data/usb/auto-mount.sh %k /mnt/usb"
KERNEL=="sd[a-z][0-9]", SUBSYSTEM=="block", ACTION=="remove", RUN+="/data/usb/auto-mount.sh %k /mnt/usb"
#### CF Card
KERNEL=="hd[a-z]", SUBSYSTEM=="block", ACTION=="add", RUN+="/data/usb/auto-mount.sh %k /mnt/cf"
KERNEL=="hd[a-z]", SUBSYSTEM=="block", ACTION=="remove", RUN+="/data/usb/auto-mount.sh %k /mnt/cf"
KERNEL=="hd[a-z][0-9]", SUBSYSTEM=="block", ACTION=="add", RUN+="/data/usb/auto-mount.sh %k /mnt/cf"
KERNEL=="hd[a-z][0-9]", SUBSYSTEM=="block", ACTION=="remove", RUN+="/data/usb/auto-mount.sh %k /mnt/cf"
#### SD Card
KERNEL=="mmcblk[0-9]p", SUBSYSTEM=="block", ACTION=="add", RUN+="/data/usb/auto-mount.sh %k /mnt/sd"
KERNEL=="mmcblk[0-9]p", SUBSYSTEM=="block", ACTION=="remove", RUN+="/data/usb/auto-mount.sh %k /mnt/sd"
KERNEL=="mmcblk[0-9]p[0-9]", SUBSYSTEM=="block", ACTION=="add", RUN+="/data/usb/auto-mount.sh %k /mnt/sd"
KERNEL=="mmcblk[0-9]p[0-9]", SUBSYSTEM=="block", ACTION=="remove", RUN+="/data/usb/auto-mount.sh %k /mnt/sd"

添加脚本

vim /data/usb/auto-mount.sh

#! /bin/sh

#-------------------------------------------------#
#磁盘种类       设备节点            设备分区节点
#USB            sd[a-z]            sd[a-z][0-9]
#CF Card        hd[a-z]            hd[a-z][0-9]
#SD Card        mmcblk[0-9]        mmcblk[0-9]p[0-9]
#-------------------------------------------------#

DEV_NAME=$1 #参数1:设备分区
DEV_PATH=$2 #参数2:挂载位置
DEV_SUFF=$(echo $DEV_NAME | sed 's/[a-z]//g')

DEV_PATH=$DEV_PATH$DEV_SUFF

if [ $ACTION == "add" ] ; then
  sudo mkdir -p $DEV_PATH
  sudo umount $DEV_PATH
  sudo /usr/sbin/mount.exfat /dev/$DEV_NAME $DEV_PATH
  if [[ $? -ne 0 ]] ; then
    sudo umount $DEV_PATH
    sudo /usr/sbin/mount.ntfs /dev/$DEV_NAME $DEV_PATH
  fi
  if [[ $? -ne 0 ]] ; then
    sudo umount $DEV_PATH
    sudo mount -o iocharset=utf8 /dev/$DEV_NAME $DEV_PATH
  fi
  if [[ $? -ne 0 ]] ; then
    sudo umount $DEV_PATH
    sudo rmdir $DEV_PATH
  fi
elif [ $ACTION == "remove" ] ; then
  if [[ -e $DEV_PATH ]] ; then
    sudo umount $DEV_PATH
    sudo rmdir $DEV_PATH
  fi
fi

exit 0

sudo才能成功挂载ntfs格式

加载规则

udevadm control --reload

还学到了一个命令lsblk,如果只是查看存储设备挂载信息相比dffdisk要清晰很多。