From the office of “this actually happened to me recently,” it is possible to accidentally remove yourself from the sudo group, thereby rendering your account incapable of running any action that requires administrative privileges. This isn’t a problem if you have other users on your system that have administrative privileges. But if you’re the lone user, what do you do?
You follow the steps I’m going to outline below. I’m going to demonstrate this on a Ubuntu 16.04 Server installation, wherein the user has been removed from sudo and cannot undertake a single command that requires them to make use of sudo–such as solving this problem.
The process is actually quite simple.
The first thing you must do is boot into recovery mode. To do this, reboot your machine, and at the initial GRUB menu, select Advanced options for Ubuntu (using your keyboard down arrow – Figure A). Hit Enter on your keyboard.
In the next window (Figure B), use the down arrow to select the recovery mode for the latest kernel installed on your system and hit Enter on your keyboard.
You will finally find yourself at the Recovery Menu (Figure C). Using the keyboard arrow, scroll down and select root. Hit Enter on your keyboard. When prompted, hit Enter again on your keyboard and you’ll be dumped into the recovery root prompt.
Adding yourself back to sudo
All you have to do now is run a single command to re-add your user to the sudo group. That command is:
usermod -a -G sudo USER
Where USER is the user to be added.
You should receive no errors (no output at all actually). If you do receive an error that the system cannot lock /etc/passwd, you need to remount the drive in rw mode with the command mount -o remount, rw /. That should solve the lock issue.
Once this is complete, issue the command reboot and your system will reboot. When you’re presented with the login prompt, log back into your machine as the newly repaired user. Issue the command sudo apt update to see if you’re prompted for the sudo password and the update command runs. If all goes as expected, your user is repaired and you can continue working with your machine as per normal.
That was simple.
Sudo with caution
When you’re modifying users with the help of sudo, make sure to do so with care. Say you attempted to add a user to the docker group with the command sudo usermod -G docker USER (where USER is the name of the user). That command would modify the user such that it would only belong to the docker group. The correct command would be sudo usermod -a -G docker USER.
Always sudo with caution.