DevOps by Default Blog

Mounting raw disk images on Linux

From time to time you may have a raw disk image that you have made with the dd tool, or something similar. If it’s a backup of a single partition then it can be mounted in Linux using the loopback feature pretty easily, so long as you know the filesystem type, such as ext4, vfat or ntfs for example:

$ sudo mkdir -p /mnt/loop
$ mount -t ntfs -o loop /path_to_disk_image.img /mnt/loop
$ ls -lart /mnt/loop
$ sudo umount /mnt/loop

Partition table in the image

Usually we can’t mount the whole image, because it may have a partition table and even multiple partitions defined. Fortunately, kpartx can create mapper entries to access those. You first check to see what is in the image with:

$ fdisk -l /path_to_disk_image.img
Disk /path_to_disk_image.img: 49.68 MiB, 52093440 bytes, 101745 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
Disklabel type: windows
Disk identifier: 0x00000000

Device                                                          Boot Start    End Sectors  Size Id Type
/path_to_disk_image.img *       17 101625  101609 49.6M  6 NTFS

Mapper entries

Let’s use kpartx to create mapper entries to access the partition:

$ sudo kpartx -av /path_to_disk_image.img
add map loop35p1 (253:9): 0 101609 linear 7:35 17

Then we need somewhere to mount the image partition:

$ sudo mkdir -p /mnt/loop35p1

If you know the filesytem type, specify it with the -t parameter. If you’re not sure, linux may be able to guess it if you use -t auto.

$ sudo mount -t ntfs -o loop /dev/mapper/loop35p1 /mnt/loop35p1/
$ ls -lart /mnt/loop35p1/

Cleaning up

Once we have copied out any data we were looking for (or even written to the image if we wanted), then we should unmount and clean up:

$ sudo umount /mnt/loop35p1/
$ sudo kpartx -dv /path_to_disk_image.img
del devmap : loop35p1
loop deleted : /dev/loop35