Mounting a QCOW2 Partition

I run an instance of FreeDOS 1.2 in a qemu virtual machine. To get files in and out, I occasionally mount the main partition of the virtual machine's disk image. It gets a bit complicated, so I wrote a script.

Much of what I did is from documentation on the net. But combining into a script makes life easier.

Warning: Do not run the VM while the virtual disk is mounted. Doing so is asking for trouble.

Which means unmounting the partition after you're done.

umount /mnt && partx --delete /dev/nbd0 && qemu-nbd --disconnect /dev/nbd0

Here's the complete script.

I doubt your user name is charles, and I doubt your virtual partition is in the same location as mine, so you get to edit those. And your device names are likely different as well.

# A shell script to mount the freedos virtual machine's virtual
# disk.

# Be sure to umount the partition and disconnect when you are done:

# umount /mnt && partx --delete /dev/nbd0 && qemu-nbd --disconnect /dev/nbd0

# per http://ask.xmodulo.com/mount-qcow2-disk-image-linux.html

runUser=root                    # execute as this user only.
virtualDisk=/var/lib/libvirt/images/FreeDOS.1.2.qcow2

# This is the user for whom we will mount the virtual drive, so this
# user may read from and write to the virtual drive.
user=charles

if [ "$USER" != "$runUser" ] ; then
  echo Wrong user: you must be $runUser to run this script!
  exit 1
fi

# Mount wants the uid and gid of the intended user, rather than the
# user name, so we get them.

uid=$(grep ${user} /etc/passwd | cut -d: -f 3)
gid=$(grep ${user} /etc/passwd | cut -d: -f 4)

#  harmless if redundant.
modprobe nbd max_part=8

qemu-nbd --connect=/dev/nbd0 ${virtualDisk}

fdisk /dev/nbd0 -l

# per https://gist.github.com/shamil/62935d9b456a6f9877b5
partx --add /dev/nbd0

mount -o uid=${uid},gid=${gid} /dev/nbd0p1 /mnt/

And that's it.

blogroll

social