This post covers resetting a forgotten root password for a KVM virtual machine on CentOS/RHEL/Ubuntu Linux. If you forget your KVM virtual machine root password, you can follow these steps to reset it.
To change the root password for a VM on a KVM server, you can use a tool called guestfish. Guestfish is a shell and command-line tool that allows you to examine and modify virtual machine file systems. So, you can use this tool to edit the virtual machine file system and then modify the /etc/shadow file to change the root password.

Install Guestfish

If you don’t already have guestfish installed, use these commands to install it:
  • For CentOS/RHEL/Rocky/AlmaLinux
  • For Fedora or newer versions of CentOS or RHEL derivatives:
  • For Ubuntu/Debian:

Shutdown the VM

Get the path of the storage device for the guest OS

Create a new encrypted password

If you already have an encrypted password hash, you can use that and skip this step.
If you need to encrypt a password, use this OpenSSL command:

Use the guestfish utility to access the device

Use guestfish to open the file or device in read-write mode.

Use guestfish to mount the device

In the example above, the ‘/’ file system is /dev/sda2 so the last command mounts it at ‘/’.

Change the password

To change the password for the root user, you will need to edit the ‘/etc/shadow’ file with either vi or emacs.
Find the line containing the root user and replace the old password with the new password. Save and close the file.

Quit Guestfish

Start the VM back up

You should be able to login using your new password.
Share this article

Join the newsletter

Join thousands of satisfied readers.