You are here

Reactie toevoegen

Mounting a disk image file with partitions

In Linux you can easily make a backup of a whole disk, including MBR (partition table) and different types of filesystems with dd. While this is very useful, how can you access individual partitions later without "extracting" them from the image? "kpartx" is the command you need.

The usage is very straightforward:

kpartx -a /path/to/disk_image

You'll find a block device for each partition in /dev/mapper/loopXpY

If you want to properly disconnect everything, you'll need to use these commands:
kpartx -d /path/to/disk_image

For a more technical background: what needs to be done is to attach the image file to a "loop" device (so the file can be accessed as if it was a block device). Then the partition table needs to be read and additional block devices need to be mapped to the correct regions of the block device. These different block devices make it possible to access just "one partition" of the drive.

If it wasn't for kpartx you'd need to use different tools such as losetup, fdisk or parted, dmsetup. There are a lot of possible ways of doing this, in most of them you'll need to use a partitioning tool to read the partition table, a calculator (or mental arithmetic) to calculate offsets, losetup or mount -o loop,offset=xxx to get access to the partitions. With dmsetup you can define all partitions and offsets in a "table file".

For the removal of all devices you would need dmsetup -d /dev/mapper/loopXpY. As always, umount partitions first. You'll also notice if you use dos partition tables with extended partitions, you first need to remove all secondary partitions before you can remove the "primary extended partition". When all mapped partitions (in /dev/mapper) are gone, you can remove the loopback device with losetup -d /dev/loopX.

If you don't want to change the original image file (or you simply can't because it's on a read-only device), you could also use dd to copy a specific part from the image file. With the "bs" option of dd, you specify the block-size and the unit of the "skip", "seek" and "count" options. With these options you can tell dd at which offset to start reading (skip), at which offset to start writing in the output file (seek) and how many blocks you want to copy (count).