How to mount a virtual box disk image on the host

Sometime (e.g. when a machine is not booting anymore) it is necessary to fix some stuff by editing the root filesystem. Luckily this is much more simple when using virtual machine, than with real hardware. When a virtual machine is shut down, you can mount the virtual disk image on the host system and do not have to try to boot some kind of rescue system. Most important part of this is the qemu-nbd command. If not already installed, get it by e.g.

apt-get install qemu-utils

on a debian system. Then you can use a vdi file with

qemu-nbd -c /dev/nbd1 

If you get a

Failed to open /dev/nbd1: No such file or directory

then your kernel does not have the nbd module loaded already.

modprobe nbd max_part=8

will do the trick. If your image has more then 8 partition, you might want to increase that, but it seems to be the default on the internet.

Now the virtual disk image is available including its individual partitions as /dev/nbd1pX. So a simple

mount /dev/nbd1pX /mnt

allows fixing the stuff. Unmounting happens in the reverse order:

umount /mnt
qemu-nbd -d /dev/nbd1    # disconnects the image
rmmod nbd