通过文件挂载USB

通过文件挂载USB

我的系统连接了多个 USB。我想找到一个包含特定 .ini 文件或为空的 USB(在这种情况下我想创建 .ini 文件)并将其安装在 /media/mount_point 处。如果不存在这样的 USB,则不应安装任何内容。

我尝试创建一个 udev 规则,为每个 USB 运行以下脚本:

#!/bin/sh

LOGFILE="/home/user/mount.log"
MOUNTDIRECTORY="/media/mount_point"

if [ -z "$DEVNAME" ]; then
  exit
fi

echo "USB device detected at $DEVNAME" >> $LOGFILE

if grep '$MOUNTDIRECTORY ' /proc/mounts; then
  # Already mounted
  echo "Mount directory already in use" >> $LOGFILE
  exit
fi

mount $DEVNAME $MOUNTDIRECTORY -o umask=0000,gid=1000,uid=1000 &>> $LOGFILE

if [ $? -eq 0 ]; then
    echo "$DEVNAME mounted at $MOUNTDIRECTORY" >> $LOGFILE
    if [ -f $MOUNTDIRECTORY/log.ini ]; then
        echo "Log.ini found. Ready to log" >> $LOGFILE
        break
    elif [ -z "$(ls -A $MOUNTDIRECTORY)" ]; then
        echo "USB device empty. Creating log.ini" >> $LOGFILE
        touch $MOUNTDIRECTORY/log.ini
        break
    else
        umount $MOUNTDIRECTORY
    fi
else
    echo "Failed to mount $DEVNAME at $MOUNTDIRECTORY" >> $LOGFILE
fi

echo "" >> $LOGFILE

如果 .ini 存在(编辑 systemd-udevd.service 后),则此方法有效这个问题),但如果找到空 USB,则不会。 $LOGFILE 输出报告已创建 .ini,但如果我检查,则已安装的设备上没有 .ini 文件。如果卸载,我会发现 .ini 文件已在安装点创建。

为什么 .ini 文件最终出现在装载点而不是装载的 USB 上?我怎样才能解决这个问题?

或者,对于这个问题是否有比 udev 更好的方法?

答案1

我已经能够找到满意的解决方案。

我没有尝试直接从 udev 挂载,而是按照中的建议生成了一个新服务这个问题。最终我得到了这个 udev 规则:

ACTION=="add",<Your device specifiers here>,ENV{SYSTEMD_WANTS}="log@$env{DEVPATH}.service"

添加了以下服务/etc/systemd/system

[Service]
Type=oneshot
TimeoutStartSec=300
GuessMainPID=false
RemainAfterExit=yes
ExecStart=/bin/bash -c "/home/user/mount.sh %I"

并将我的脚本修改为:

#!/bin/sh

LOGFILE="/home/user/mount.log"
MOUNTDIRECTORY="/media/mount_point"
DEVPATH=$1
BASENAME="$(basename $DEVPATH)"
DEVICE="/dev/$BASENAME"

if [ -z "$BASENAME" ]; then
  exit
fi

echo "" >> $LOGFILE
echo "New USB device detected at $DEVICE" >> $LOGFILE

if grep '$MOUNTDIRECTORY ' /proc/mounts; then
  # Already mounted
  echo "Mount directory already in use" >> $LOGFILE
  exit
fi

mount $DEVICE $MOUNTDIRECTORY -o umask=0000,gid=1000,uid=1000 >> $LOGFILE

if [ $? -eq 0 ]; then
    echo "$DEVICE mounted at $MOUNTDIRECTORY" >> $LOGFILE
    if [ -f $MOUNTDIRECTORY/log.ini ]; then
        echo "Log.ini found. Ready to log" >> $LOGFILE
        break
    elif [ -z "$(ls -A $MOUNTDIRECTORY)" ]; then
        echo "USB device empty. Creating log.ini" >> $LOGFILE
        touch $MOUNTDIRECTORY/log.ini
        break
    else
        echo "Log.ini not found. Unmounting" >> $LOGFILE
        umount $MOUNTDIRECTORY
    fi
else
    echo "Failed to mount $DEVICE at $MOUNTDIRECTORY" >> $LOGFILE
fi

echo "" >> $LOGFILE

我仍然不明白最初问题的原因(log.ini 文件出现在安装点而不是安装的设备之一)。如果有人有解释,我会很感兴趣。

相关内容