How to mount a VirtualBox VDI image

Don’t believe the hype! It is entirely possible to mount a VirtualBox VDI image, just like a loopback filesystem… all you need are the right tools and know-how. Allow me to illustrate.

My apologies, that was the wrong illustration. Onward!

Before we start, it should be noted that you don’t want to do this while your disk image is already in use. That is to say, if you’re running a virtualised host using this image, GTFO.

First, install the QEMU tools. In Ubuntu, you’ll find them in the qemu-kvm package. Whatever package your distribution ships which contains the qemu-nbd binary should be fine.

Load the nbd kernel module. Yes, I’m serious, the network block device module! (Note: All of the following commands require superuser permissions, so escalate your privileges in whatever way makes you most comfortable.)

modprobe nbd

Then run qemu-nbd, which is a user space loopback block device server for QEMU-supported disk images. Basically, it knows all about weird disk image formats, and presents them to the kernel via nbd, and ultimately to the rest of the system as if they were a normal disk.

qemu-nbd -c /dev/nbd0 <vdi-file>

That command will expose the entire image as a block device named /dev/nbd0, and the partitions within it as subdevices. For example, the first partition in the image will appear as /dev/nbd0p1.

Now you could, for instance, run cfdisk on the block device, but you will most likely want to mount an individual partition.

mount /dev/nbd0p1 /mnt

Gadzooks! Now you can muck around inside the filesystem to your heart’s content. Go ahead and copy stuff in or out, or if you’re feeling fruity, have some chrooty: chroot /mnt.

When you’re done, unmount the filesystem and shut down the qemu-nbd service.

umount /mnt
qemu-nbd -d /dev/nbd0