Mounting Whole Disk Images with kpartx

So you just rescued your data from a dying harddisk using ddrescue /dev/sdd backup.img and now you wonder how to get your data out of that image?

When you google “mount whole disk image”, you will find a lot of posts showing how to manually calculate the offset of each partition and then mount them by manually specifiying the partition offset. That’s a lot of work and easy to get wrong.

Luckily there’s a much better method: kpartx can create the required partition mappings in /dev/ so you access the image as if it were a real disk. In most distributions it is part of the multipath-tools package, so install that using your favourite package manager.

Now you can activate the mapping with

1
2
3
$ kpartx -va backup.img
add map loop0p1 (254:0): 0 102400 linear /dev/loop0 2048
add map loop0p2 (254:1): 0 100352 linear /dev/loop0 104448

and then simply mount the partitions as usual:

1
2
3
$ mount /dev/mapper/loop0p1 data
$ ls data
important_files

When you’re done unmount everything and remove the mapping:

1
2
3
4
5
$ umount data
$ kpartx -vd backup.img
del devmap : loop0p2
del devmap : loop0p1
loop deleted : /dev/loop0

And that’s it!

Troubleshooting

If you get this error:

1
2
3
$ kpartx -va backup.img
mount: could not find any device /dev/loop#Bad address
can't set up loop

you’re missing the loop kernel module. Just load it with

1
$ modprobe loop