Intro
Recently I found myself locked out of a VM that I have hosted using KVM. Unfortunately, I could no longer remember my account’s password, and I hadn’t saved it in my password locker.
The VM (domain) is running Ubuntu Xenial 16.04.1, and the image type is a qcow2. KVM is running on Debian Jessie 8.6.
Mounting the VMs Image
After searching for someone with a similar problem, I found this page which got me started.
Important: Be sure that your VM (domain) is shutdown before proceeding. (Follow steps 2-4 on that guide)
Once I got to step 6, I realized that they were using .img images instead of qcow2. Next, I found this page which showed me how to mount a qcow2 image to my host. Not knowing exactly how my images were set up, I started following the guide from the 4th paragraph “To mount qcow2 images …”
Here’s an example of the commands I ran
modprobe nbd max_part=63 qemu-nbd -c /dev/nbd0 <path to qcow2 image> mkdir -p /mnt/image mount /dev/nbd0p1 /mnt/image
Once I got to the next paragraph which talked about LVM, none of the commands worked, and I realized I wasn’t using LVM. At this point, I tried browsing to /mnt/image/
and saw that it had, in fact, mounted the image properly.
Editing /etc/shadow
So I went back to the original guide I found. Step 13 shows how to edit /etc/shadow
to remove an account’s password.
Basically just remove the encrypted password. You can read more about /etc/password
on this nixCraft page.
Example:
Old:
root:$8$gbwrd7.g/:5345:0:99999:7:::
New:
root::5345:0:99999:7:::
Important: To allow you to SSH into the machine, you’ll either need to go into /etc/ssh/sshd_config
and enable empty passwords, or copy a public key into the user’s ~/.ssh/authorized_keys
file. (I chose the latter.)
Unmount and cleanup
Now it’s time to unmount the disk from the system and qemu-nbd. To do that, run these two commands. In the second guide that I linked to, they mention running killall qemu-nbd
instead of qemu-nbd -d /dev/nbd0.
I don’t think that’s a good idea. Someone in the comments mentioned using the qemu-nbd -d
command, which seems to properly disconnect the image.
umount /mnt/image qemu-nbd -d /dev/nbd0
Start the VM and Set a New Password
You can now start the VM using virsh start <domainname>
Once you are logged in, you can use the passwd
command with no arguments to set a password for your account.