Regaining root access to a virtual machine with Guestfish

Passwordless users with SSH public/private key access is a great way to go, but this requires a user to have passwordless sudo rights if it is to have sudo at all.

A couple of times now I have locked my user out of a having root access on a VM via various methods. – I still am able to get into the machine, but not use sudo, and no other user can use sudo either. What now?

If you have root access to the host machine and you’re able to install libguestfs, you can recover it. NOTE: Ubuntu 12.04 is the first Ubuntu version to have the libguestfs package available in the repository.

I have fixed both Ubuntu 10.04 and 12.04 Virtual Machines of the qcow2 format. Guestfish claims it can do many other formats. I used a Ubuntu 12.04 host machine to run guestfish. This will install the libguestfs package and any other dependencies you don’t already have:

sudo apt-get update
sudo apt-get install guestfish
Be sure to shutdown the VM before making any changes with guestfish. You are likely to corrupt your VM if you try to use guestfish in read/write mode while the VM is running.

Now we will open the sudoers file on the VM:

sudo guestfish --rw -a /path/to/vm_file.qcow2 -i edit /etc/sudoers

Make sure to add the following line at the end of the file, since other sudoer lines may override it otherwise:


where [USERNAME] is your user on the VM. Mine looked like this:

davidamick ALL=(ALL) NOPASSWD: ALL

Now save the file, close the editor, and restart the VM to find your user able to gain root without using it’s non-existent password. 🙂 It’s a good idea to then continue to set it up in whatever more proper way you use normally, like adding your user to an admin group who has the NOPASSWD: directive, and removing the line you just added. P.S. Guestfish is very powerful, and is also capable of adding a password to a root or other user. If you need to do this, try using guestfish’s “command” command to run a command inside the VM. You would not however want to run any command that requires user feedback, (I.E. the “passwd” command) since guestfish will hang and not play nice with this (as I found out the hard way.) Instead, practice first on a separate machine using the “crypt” and “usermod” commands to change the password in a single command, then run that command with guestfish on the VM.

UPDATE: Here is an example of adding a new password:

command "bash -c 'echo davidamick:asdfasdf | chpasswd'"

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s