Mounting VirtualBox VDI images (and similar formats)

Sometimes you have a .vdi (or .vmdk or similar) virtual machine disk image, and you wish to access files inside, without starting the virtual machine itself and copying files via network or some ‘guest additions’ tools provided by the virtualization software.

To do this, you need nbd support enabled in the kernel (and module inserted) and qemu installed (which is actually another virtualization software, but we need it for the qemu-nbd utility).

In some distributions, the nbd module is enabled by default, on some you have to enable it when compiling the kernel sources.

  │ Symbol: BLK_DEV_NBD [=m]
  │ Type  : tristate
  │ Prompt: Network block device support
  │   Location:
  │     -> Device Drivers
  │       -> Block devices (BLK_DEV [=y])
  │   Defined at drivers/block/Kconfig:276
  │   Depends on: BLK_DEV [=y] && NET [=y]

Due to some weird reasons, the nbd module by default supports zero (0) partitions inside a block device:

# modinfo nbd
filename:       /lib/modules/4.9.6-gentoo-r1/kernel/drivers/block/nbd.ko
license:        GPL
description:    Network Block Device
depends:        
intree:         Y
vermagic:       4.9.6-gentoo-r1 SMP mod_unload 
parm:           nbds_max:number of network block devices to initialize (default: 16) (int)
parm:           max_part:number of partitions per device (default: 0) (int)

So when inserting the module, set the parameter to a larger number (eg. 4 or 16 or whatever)

modprobe nbd max_part=16

After that, you use the qemu-nbd utility to ‘connect’  the vdi image to the nbd block device (qemu-nbd actually works as a block device server), mount the partition, do stuff, umount the partition, and disconnect the qemu-nbd:

#connect the device:
qemu-nbd -c /dev/nbd0 /path/foo.vdi
#partitions appear as /dev/nbd0p1, /dev/nbd0p2...
mount /dev/nbd0p1 /mnt
#do stuff
umount /mnt
#and now disconnect the device:
qemu-nbd -d /dev/nbd0