Skip to content

Instantly share code, notes, and snippets.

@ChenYFan
Created November 30, 2025 15:05
Show Gist options
  • Select an option

  • Save ChenYFan/94beab4b701bab110b0b1ff7702db41e to your computer and use it in GitHub Desktop.

Select an option

Save ChenYFan/94beab4b701bab110b0b1ff7702db41e to your computer and use it in GitHub Desktop.
Ubuntu挂载VHD用脚本(自用)
#!/bin/bash
function show_help() {
echo "Usage: $0 [mount|unmount] [VHD/VHDX file or mount point]"
echo "Commands:"
echo " mount [VHD/VHDX file] [Disk partition number] [Mount point] Mount the specified VHD/VHDX file"
echo " unmount [mount point] Unmount the specified mount point"
echo " help Show this help message"
}
function find_free_nbd() {
for i in {0..15}; do
if ! sudo nbd-client -c /dev/nbd$i &> /dev/null; then
echo "/dev/nbd$i"
return
fi
done
echo ""
}
if [ $# -eq 0 ] || [ "$1" == "help" ]; then
show_help
exit 0
fi
COMMAND=$1
if [ "$COMMAND" == "mount" ]; then
if [ $# -ne 4 ]; then
echo "Error: mount command requires 3 arguments."
show_help
exit 1
fi
VHD_FILE=$2
PARTITION_NUM=$3
MOUNT_POINT=$4
NBD_DEVICE=$(find_free_nbd)
if [ -z "$NBD_DEVICE" ]; then
echo "Error: No free nbd device available."
exit 1
fi
sudo qemu-nbd -c "$NBD_DEVICE" "$VHD_FILE"
sudo partprobe "$NBD_DEVICE"
PARTITION_DEVICE="${NBD_DEVICE}p${PARTITION_NUM}"
#注:这里是为了适配NyirusuDataCenter的Samba权限组,设置到了uid和gid。实际使用应当修改为自己的或者删除
#不用loop可能会出现性能下降(鬼知道为什么直接读取nbd速度会轧钢)
sudo mount -o loop,rw,uid=1002,gid=1002 "$PARTITION_DEVICE" "$MOUNT_POINT"
echo "Mounted $VHD_FILE partition $PARTITION_NUM to $MOUNT_POINT using $NBD_DEVICE"
elif [ "$COMMAND" == "unmount" ]; then
if [ $# -ne 2 ]; then
echo "Error: unmount command requires 1 argument."
show_help
exit 1
fi
MOUNT_POINT=$2
#先用mount命令查找实际挂载点的设备(先找,不要先umount,不然找不到了)
#不要用findmnt(这会找到loop设备),尝试直接从mount命令的输出中获取
MOUNT_INFO=$(mount | grep "on $MOUNT_POINT ")
if [ -z "$MOUNT_INFO" ]; then
echo "Error: Mount point $MOUNT_POINT is not mounted."
exit 1
fi
DEVICE=$(echo "$MOUNT_INFO" | awk '{print $1}')
sudo umount "$MOUNT_POINT"
NBD_DEVICE=$(lsblk -no PKNAME "$DEVICE")
sudo qemu-nbd -d "/dev/$NBD_DEVICE"
echo "Unmounted $MOUNT_POINT and detached $NBD_DEVICE"
else
echo "Error: Unknown command '$COMMAND'."
show_help
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment