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:

  1. Reboot the system.

  2. Interrupt the boot loader countdown by pressing any key, except Enter.

  3. Move the cursor to the kernel entry to boot.

reset root password RHEL 8
  1. Press e to edit the selected entry.

  2. Move the cursor to the kernel command line (the line that starts with Linux).

reset root password CentOS 8
  1. Append rd.break. With that option, the system breaks just before the system hands control from the initramfs to the actual system.
append rd.break reset root password RHEL 8
  1. 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.
recover root password RHEL 8

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:

  1. Remount /sysroot as read/write.

    switch_root:/# mount -o remount,rw /sysroot
    
  2. Switch into a chroot jail, where /sysroot is treated as the root of the file-system tree.

    switch_root:/# chroot /sysroot
    sh-4.4#
    
  3. Set a new root password.

    sh-4.4# passwd root
    
set new password in rescue mode RHEL 8
  1. Make sure that all unlabeled files, including /etc/shadow at this point, get relabeled during boot.

    sh-4.4# touch /.autorelabel
    
  2. 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.