linux挂载镜像文件
方法一(初级)
- 先查看第一个空闲loop设备
sudo losetup -f
/dev/loop0
- 使用上一步得到的设备名,第一次创建loop设备
sudo losetup /dev/loop0 archlinux-2008.06-core-i686.img
- 查看信息
sudo fdisk -lu /dev/loop0
Disk /dev/loop0: 322 MB, 322469376 bytes
53 heads, 12 sectors/track, 990 cylinders, total 629823 sectors
Units = sectors of 1 * 512 = 512 bytes
Disk identifier: 0x00000000
Device Boot Start End Blocks Id System
/dev/loop0p1 * 63 629822 314880 83 Linux
Partition 1 has different physical/logical beginnings (non-Linux?):
phys=(0, 1, 1) logical=(0, 5, 4)
Partition 1 has different physical/logical endings:
phys=(39, 52, 12) logical=(990, 15, 3)
我们可以看到,该镜像只有一个分区(loop0p1),从第63扇区开始(Start列),每扇区512字节(Units = sectors of 1 * 512 = 512 bytes),我们算出offset,下面mout命令会用到:
- mout
sudo losetup -o $((63*512)) /dev/loop1 archlinux-2008.06-core-i686.img
sudo mount -o loop /dev/loop1 /mnt/
ls /mnt/
addons archlive.sqfs boot lost+found
事实上,fdisk可以直接查看img文件(虽然功能不全,下面会说到),mount可以自动创建loop设备,所以上面步骤可以简化为: I. 查看信息
sudo fdisk -lu archlinux-2008.06-core-i686.img
You must set cylinders.
You can do this from the extra functions menu.
Disk archlinux-2008.06-core-i686.img: 0 MB, 0 bytes
53 heads, 12 sectors/track, 0 cylinders, total 0 sectors
Units = sectors of 1 * 512 = 512 bytes
Disk identifier: 0x00000000
Device Boot Start End Blocks Id System
archlinux-2008.06-core-i686.img1 * 63 629822 314880 83 Linux
Partition 1 has different physical/logical beginnings (non-Linux?):
phys=(0, 1, 1) logical=(0, 5, 4)
Partition 1 has different physical/logical endings:
phys=(39, 52, 12) logical=(990, 15, 3)
第一行抱怨不能得到cylinders,原因是普通文件上没有实现ioctl操作,我们可以看到0 cylinders,但这对我们不重要,关键是我们依然可以得到第一个分区(archlinux-2008.06-core-i686.img1)的偏移值
II. 直接mount
sudo mount -o loop,offset=$((63*512)) archlinux-2008.06-core-i686.img /mnt/
ls /mnt/
addons archlive.sqfs boot lost+found
方法二(高级)
查看分区|过滤前面是三个空格的行|格式化成单个空格分割|去掉行开始的空格|选择第一行|第2列数据
StartSector=`gdisk -l usb.img | grep "^ " | fmt -u -s | sed -e 's/^[ \t]*//' | head -1 | cut -d " " -f 2`
sudo mount -o loop,offset=$((StartSector*512)) usb.img /mnt/boot
利用内核模块加载参数加载
重新加载内核模块可以自动加载分区,一般情况下,nbd模块不是內建,可以自由加载和卸载,loop模块如果是內建的时候,可以使用nbd模块来加载
rmmod loop
modprobe loop max_part=16
losetup -f debian.img
rmmod nbd
modprobe nbd max_part=16
qemu-nbd -c /dev/nbd0 win10.vhd
# 如果仍然无法正确挂载分区
# 用这个命令删除加载的内核模块后,重新加载
modprobe nbd -r
modprobe nbd max_part=16
# 添加verbose
qemu-nbd --verbose -c /dev/nbd0 win10.vhd
利用kpartx挂载虚拟文件系统
对于內建的loop模块,没有办法自动加载分区信息,用内核模块参数加载的方法算是最好的
sudo apt-get install kpartx
# 添加分区
sudo kpartx -va /dev/nbd0
# 删除分区
sudo kpartx -vd /dev/nbd0