目的:在linux下挂载img文件,以实现对img文件的修改
# fdisk -lu arch-live-usb.img
You must set cylinders.
You can do this from the extra functions menu.
Disk arch-live-usb.img: 0 MB, 0 bytes
248 heads, 19 sectors/track, 0 cylinders, total 0 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xff978785
Device Boot Start End Blocks Id System
arch-live-usb.img1 2048 593919 295936 83 Linux
Partition 1 has different physical/logical beginnings (non-Linux?):
phys=(0, 32, 33) logical=(0, 107, 16)
Partition 1 has different physical/logical endings:
phys=(36, 247, 19) logical=(126, 10, 18))
# losetup -fo 1048576 arch-live-usb.img // 这里的 -fo 104857=(2048*512)
是指定第一个分区在整个磁盘镜像文件中的偏移量
# losetup -a // 得到 loop 设备文件路径,如 /dev/loop0
# mount /dev/loop0 /mnt
卸载: umount /mnt
losetup -d /dev/loop1
1. loop设备介绍
在类 UNIX 系统里,loop 设备是一种伪设备(pseudo-device),或者也可以说是仿真设备。它能使我们像块设备一样访问一个文件。
在使用之前,一个 loop 设备必须要和一个文件进行连接。这种结合方式给用户提供了一个替代块特殊文件的接口。因此,如果这个文件包含有一个完整的文件系统,那么这个文件就可以像一个磁盘设备一样被 mount 起来。
上面说的文件格式,我们经常见到的是 CD 或 DVD 的 ISO 光盘镜像文件或者是软盘(硬盘)的 *.img 镜像文件。通过这种 loop mount (回环mount)的方式,这些镜像文件就可以被 mount 到当前文件系统的一个目录下。
至此,顺便可以再理解一下 loop 之含义:对于第一层文件系统,它直接安装在我们计算机的物理设备之上;而对于这种被 mount 起来的镜像文件(它也包含有文件系统),它是建立在第一层文件系统之上,这样看来,它就像是在第一层文件系统之上再绕了一圈的文件系统,所以称为 loop。
2. losetup命令
losetup [ -e encryption ] [ -o offset ] loop_device file
losetup [ -d ] loop_device
此命令用来设置循环设备。循环设备可把文件虚拟成块设备,籍此来模拟整个文件系统,让用户得以将其视为硬盘驱动器,光驱或软驱等设备,并挂入当作目录来使用。
上面,命令格式中的选项与参数名:
-e 表示加密的方式
-o 设置数据偏移量
-d 卸载设备
loop_device 循环设备名,在 linux 下如 /dev/loop0 , /dev/loop1 等。
file 要与循环设备相关联的文件名,这个往往是一个磁盘镜象文件,如 *.img
3. 使用举例
(1)创建空的磁盘镜像文件,这里创建一个1.44M的软盘
$ dd if=/dev/zero of=floppy.img bs=512 count=2880
(2)使用 losetup将磁盘镜像文件虚拟成快设备
$ losetup /dev/loop1 floppy.img
(3)挂载块设备
$ mount /dev/loop0 /tmp
经过上面的三步之后,我们就可以通过/tmp目录,像访问真实快设备一样来访问磁盘镜像文件floppy.img。
(4) 卸载loop设备
$ umount /tmp
$ losetup -d /dev/loop1