How to reset or recover root password in CentOS/RHEL 8
Resetting the root password from the Boot Loader
One task that every system administrator should be able to accomplish is resetting a lost root password. If the administrator is still logged in, either as an unprivileged user but with full sudo access, or as root, this task is trivial. When the administrator is not logged in, this task becomes slightly more involved.
Several methods exist to set a new root password. A system administrator could, for example, boot the system using a Live CD, mount the root file system from there, and edit /etc/shadow. In this section, we explore a method that does not require the use of external media.
On CentOS/RHEL 8, it is possible to have the scripts that run from the initramfs pause at certain points, provide a root shell, and then continue when that shell exits. This is mostly meant for debugging, but you can also use this method to reset a lost root password.
To access that root shell, follow these steps:
Reboot the system.
Interrupt the boot loader countdown by pressing any key, except Enter.
Move the cursor to the kernel entry to boot.
Press e to edit the selected entry.
Move the cursor to the kernel command line (the line that starts with Linux).
- Append rd.break. With that option, the system breaks just before the system hands control from the initramfs to the actual system.
- Press Ctrl+x to boot with the changes. At this point, a root shell will be presented, with the root file system for the actual system mounted read-only on /sysroot.
At this point, the system presents a root shell, with the actual root file system on the disk mounted read-only on /sysroot. Because troubleshooting often requires modification to the root file system, you need to change the root file system to read/write. The following step shows how the remount,rw option to the mount command remounts the file system with the new option (rw) set.
To reset the root password from this point, use the following procedure:
Remount /sysroot as read/write.
switch_root:/# mount -o remount,rw /sysroot
Switch into a chroot jail, where /sysroot is treated as the root of the file-system tree.
switch_root:/# chroot /sysroot sh-4.4#
Set a new root password.
sh-4.4# passwd root
Make sure that all unlabeled files, including /etc/shadow at this point, get relabeled during boot.
sh-4.4# touch /.autorelabel
Type exit twice. The first command exits the chroot jail, and the second command exits the initramfs debug shell.
At this point, the system continues booting, performs a full SELinux relabel, and then reboots again.