How to fix sudoers file on virtual machine without root and reboot

This is not a general solution, but I'm posting this as an inspiration for people in the same situation.

I didn't have access to solutions mentioned so far but I was very lucky to have access to a cron task that ran as root. I used that cron task to run another script that fixed /etc/sudoers and from now on I will use only visudo.

So if you are in this situation cron tasks can be helpful. No downtime/server restart and no risk to mess up data with dd.


Just an unverified idea:

On a host system you have access to the image of the guest partition, right ? You can't easily mount that image since it's in use. But you don't need to mount the partition to edit a single file.

  1. Find the sudoers file sector in the partition - either use the text search for some phrase that you know exists in your sudoers file and not frequently appears at other files, like # This file MUST be edited with the 'visudo' command as root. Probably you may use for that some GUI hex editor, alternatively I believe grep can do the job here too.

    Or maybe you can discover the sector where sudoers file resides from within the guest OS...

  2. Use hex editor to edit file directly on disk, or use dd - copy sector to text file, edit it and copy it back to the original sector.

Difficulties: 1. maybe the file is cached inside the guest OS, probably you will find a way to flush caches. 2. With text search you may find several files looking like your sudoers, like deleted versions of it, either you find-out which is the right one or fix all of them.


I have experienced a similar sudoers problem on my Synology NAS device.

My solution was to put the following command into the "Task Scheduler"

chmod 0755 /etc/sudoers

Which I set to run as a root.

Although my problem was permissions related, I bet a properly configured command line series of output redirections would clear out the file and replace the contents with a basic shell that would get you back up and running.

Something like:

echo "Defaults syslog=authpriv" > /etc/sudoers

echo "%administrators ALL=(ALL) ALL" >> /etc/sudoers

echo "Cmnd_Alias SHELL = /bin/ash, /bin/sh, /bin/bash" >> /etc/sudoers

echo "Cmnd_Alias SU = /usr/bin/su" >> /etc/sudoers

echo "%wheel ALL=(ALL) NOPASSWD: ALL, !SHELL, !SU" >> /etc/sudoers