How To Recover The Root Password In RHEL/CentOS 7/8.x

*Console access required

Recover The Root Password

Forgetting the root password of a Linux system can be a daunting experience, especially when it comes to a production server running Red Hat Enterprise Linux (RHEL) or CentOS. The root user is the most privileged user in the system, and having access to it is essential for managing and maintaining the system. If you’ve lost or forgotten the root password for your RHEL/CentOS system, don’t worry. This blog post will show you how to recover the root password and regain access to your system. We’ll cover a simple and straightforward process that can be completed in just a few steps, ensuring that you can get back to managing your server with ease.

1. Reboot the system. When the grub boot loader selection menu appears immediately press an arrow key (up/down) to stop the auto selection countdown.

2. Select the kernel you wish to boot and press ‘e‘, this will allow you to edit the grub boot script for the selected kernel.

3. Arrow key down to the line that refers to the kernel (line starts with ‘linux’). This line contains the boot parameters passed when the kernel is loading. It’s usually the longest line in the script. In my example it wraps over 3 lines and ends with the words ‘rhgb quiet’. This may be different on your system. Put the cursor at the end of this line (Ctrl+E) and add ‘rd.break‘ to it. I am also removing the words ‘rhgb quiet’ but it’s not strictly necessary.

4. Now press Ctrl+x to start. The system will now boot with the edited script. The edit itself is only temporary, further reboots will still use the original unedited script.

5. After a short time amount of time you will be presented with the following prompt: switch_root:/#

6. At this stage we are in an ’emergency mode’ root shell and the root filesystem we need to edit is currently mounted as read-only. This can be shown if you use the command ‘mount‘ to view the current mounts.

7. To allow the /sysroot mount to be writeable enter the following command:
mount -o remount,rw /sysroot

8. We now need to run commands from the remounted root filesystem.
Enter the following command:chroot /sysroot

9. At the new prompt we can now simply use the command ‘passwd‘ to change the root password interactively.

10. The next step is important and forces SELinux to relabel the filesystem otherwise our edit to the file containing user passwords (/etc/shadow) will not persist. Enter the following command: touch /.autorelabel

11. We can exit the shell and reboot the system using Ctrl+D twice. The whole filesystem will be ‘relabelled’, so depending on size it may take a while to come back to a login prompt; but when it does you should now have root access to the system.

Leave a Reply

Your email address will not be published. Required fields are marked *