cheatsheet.zwischenspeicher.info

Some tech documentation and snippets, finally organized.
Posts tagged as libvirt

Mount a partition of a qcow2 (or raw) disk image

There are situations when you need to access a VM's disk / partition directly, e.g to reset a forgotten root password. For QEMU's qcow2 partitions this can be achieved with the "network block device" (nbd) driver and qemu-nbd from the qemu-utils package. (For "raw" disk images, see below.)

First, load the nbd kernel module:

$ modprobe nbd max_part=12

Now use the command qemu-nbd to make the disk image available as network block device:

$ qemu-nbd --connect=/dev/nbd0 /path/to/image.qcow2

fdisk can be used to list the available partitions inside the disk image:

$ fdisk -l /dev/nbd0

Finally mount the partition (in this case partition #2) to an arbitrary mount point:

$ mount /dev/nbd0p2 /path/to/mountpoint/

chroot into the directory as usual. When you're done, exit the chroot, then unmount the partition and disconnect the network block device:

$ umount /dev/nbd0p2
$ qemu-nbd --disconnect /dev/nbd0


Similarly, a partition inside a raw disk image can be mounted as loop device:

$ losetup /dev/loop0 /path/to/diskimage.img

Make the partition mappings available:

$ kpartx -av /dev/loop0

And mount the partition (here partition #1):

$ mount /dev/mapper/loop0p1 /mnt/image

Alternatively, the partition can be mounted directly: In this case its offset (in bytes) from the beginning of the disk image needs to be passed to the mount command, fdisk will provide the necessary values to calculate it.

Here an example disk image with only one partition:

$ fdisk -l netinst.img

Disk netinst.img: 32 MiB, 33554432 bytes, 65536 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xb6bdaf05

Device         Boot   Start     End   Sectors    Size   Id   Type
netinst.img1   *       2048   65535     63488     31M    b   W95 FAT32

The "Start" sector of the target partition (here 2048) needs to be multiplied with the disk's sector size, here 512 bytes. In this case the partition's offset is 512*2048=1048576 bytes:

$ mount -o loop,offset=1048576 netinst.img /path/to/mountpoint/