Mounting a Windows VM HDD as an NBD from the host OS

QEMU LogoEvery Sunday morning, the data drive from one of our QEMU VM’s is copied to the /mnt/weeklybackup folder.  This is an inelegant – but effective – method of performing a backup; it’s simply a brute-force copy of the drive while the server is still running and attached to it. However it’s still enough to access the drive, and have reliable copies of most of the data.  (We also use Crashplan Pro for proper versioned backups)

Of course, if you’re taking backups, you’re likely going to need to restore from the backup at some point.  This is a quick tutorial on how to mount your QCOW2 virtual drive inside the host system (“Dom0”) — effectively reading the hard drive from a different computer.

Firstly, disclaimer:  we’re not responsible for anything that happens on your system, even if you follow this guide perfectly.  In particular, make sure that there is no longer an active machine connected to the image – I have no idea what would happen, but I don’t trust it.

On the host, I run the following commands:

sudo mkdir /mnt/qcow
sudo qemu-nbd --connect=/dev/nbd0 /mnt/weeklybackup/data.qcow2 [1]
sudo mount /dev/nbd0p1 /mnt/qcow
cd /mnt/qcow

——————————————————-

[1] EDIT (Aug 18, 2014):

You may need to run the following command before running the connect command if you encounter this error:

'Failed to open /dev/nbd0: No such file or directory/build/buildd/qemu-2.0.0+dfsg/nbd.c:nbd_receive_request():L638: read failed'.

This command uses modprobe to load the nbd module if module loading is not done automatically:

sudo modprobe nbd max_part=16 [2]

——————————————————-

The first line uses the qemu-nbd (QEMU Disk Network Block Device Server) to connect the virtual disk image, data.qcow2, to mount point /dev/nbd0. It should also be noted that you need to use the full path when specifying the qcow image, regardless of where you run the terminal command from (i.e. just entering data.qcow2 while situated inside /mnt/weeklybackup won’t work).

From there on it’s a simple case of mounting the correct drive partition (as you can see, all it requires is adding p# to your NBD path, where # is the partition number) at mount point /mnt/qcow and moving in to it.

There you go!  Direct access to browse files on a virtual hard drive!

[2] EDIT (Sep 25, 2014): Adding nbd deletion methods and updated modprobe line

To remove the drive mappings:

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

# And then to unload nbd from memory

sudo rmmod nbd