Mounting QCOW2 Disk Images and Resetting the Root Password Without Booting the VM in Ubuntu/Debian
This guide explains how to mount a QCOW2 disk image on your host server and reset the root password without starting the virtual machine.
Step 1 – Install the nbd
package
sudo apt install nbd-client qemu-utils
Step 2 – Load the NBD kernel module
sudo modprobe nbd
Step 3 – Connect the QCOW2 image as a network block device
sudo qemu-nbd --connect=/dev/nbd0 /PATH_TO_IMAGE/image.qcow2
Step 4 – Identify partitions in the QCOW2 image
sudo fdisk -l /dev/nbd0
Step 5 – Mount the root filesystem
In many cases, the bootloader is on the first partition, so you’ll likely want to mount the second partition:
sudo mount /dev/nbd0p2 /mnt/
Step 6 – Bind required filesystems
sudo mount --bind /dev /mnt/dev
sudo mount --bind /proc /mnt/proc
sudo mount --bind /sys /mnt/sys
sudo mount --bind /run /mnt/run
Step 7 – Chroot into the mounted environment
sudo chroot /mnt
You are now inside the VM's root filesystem.
Step 8 – Reset the root password
passwd root
Follow the prompt to set a new root password.
Step 9 – Exit and unmount all filesystems
exit
sudo umount /mnt/run
sudo umount /mnt/dev
sudo umount /mnt/proc
sudo umount /mnt/sys
sudo umount /mnt
Step 10 – As the last step, disconnect and unload the kernel module
sudo qemu-nbd --disconnect /dev/nbd0
sudo rmmod nbd