Archive for September, 2013

Mounting an ext4 partition from a full-disk image in Linux

Friday, September 13th, 2013

Before wiping a harddrive and sending it out to be recycled, I always make a complete image of it using dd in case I need to retrieve data from it after it’s gone. The procedure is extremely simple, and is well documented all over the internet. Surprisingly, there’s far less information out there on how to mount the partitions and retrieve data one the image is created.

Let’s say you have a complete dump of an entire harddrive and its partitions stored at /mnt/server/dd_images/old_wd_120gb.img and you’d like to access data stored on one of the partitions of that image. Use parted to determine the offset of the partition you’re interested in within the image file:

root@debian:/home/todd# parted /mnt/server/dd_images/old_wd_120gb.img
GNU Parted 2.3
Using /mnt/server/dd_images/old_wd_120gb.img
Welcome to GNU Parted! Type 'help' to view a list of commands.

Tell parted to display all information in bytes beforing printing the partition table:

(parted) unit B

Print the partition table:

(parted) print
Model:  (file)
Disk /mnt/server/dd_images/old_wd_120gb.img: 120034123776B
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start          End            Size           Type      File system     Flags
 1      1048576B       115128401919B  115127353344B  primary   ext4            boot
 2      115129449472B  120033640447B  4904190976B    extended
 5      115129450496B  120033640447B  4904189952B    logical   linux-swap(v1)

We can now see that the first partition, an ext 4 bootable partition, begins at offset 1048576. Take note of this number: we’ll use it in our mount invocation later on.

Quit parted:

(parted) quit

Next, using the above offset you found with parted, use mount to mount partition directly:

root@debian:/home/todd# mount -o loop,offset=1048576 /mnt/server/dd_images/old_wd_120gb.img /mnt/ext4_partition

In most newer environments, mount will automatically create a loop device for you and use that during the mounting process. However, if you’re in an older environment or running with outdated tools and cannot upgrade, you can always manually create the loop device with losetup and then mount it:

root@debian:/home/todd# losetup -o 1048576 /dev/loop0 /mnt/server/dd_images/old_wd_120gb.img
root@debian:/home/todd# mount /dev/loop0 /mnt/ext4_partition/

If you take this route, you may need to destroy the loop device after you unmount:

root@debian:/home/todd# umount /mnt/ext4_partition
root@debian:/home/todd# losetup -d /dev/loop0

Once you’ve got your partition mounted, you can access it just as you would normally access any other filesystem.