Recover lost root password on Centos / Redhat version 7 or 8 systems
- You will need console access – either a physical keyboard and monitor locally, or using the Virtual Machine remote console. You will need to be able to control the boot process.
- Reboot the machine. When the bootloader selection screen comes up tap the up arrow to pause the boot process.
- Select the kernel you want to boot into, and hit ‘
e
‘: This will take you into a screen where you can edit the grub bootloader script. - We need to edit a specific line
- For CentoOS or Redhat 7, the line starts with ‘linux16’.
- For CentOS or Rehdat 8 the line starts with ‘
linux
‘.
- Use the arrow keys to move the cursor to the end of the line and add ‘rd.break’ at the end of that line
- Now hit
Ctrl-x
to boot bootloader script – note the change is not saved – so next time you start the system it will boot normally. - You’ll boot to a ‘rescue’ prompt that looks like this:
switch_root:/#
. - Remount the root partition in read-write mode so that you can run commands. Enter the following:
mount -o remount rw /sysroot
and then hit ENTER. - Now type
chroot /sysroot
and hit enter. This will change you into thesysroot (/)
directory, and make that your path for executing commands. - Reset the root password using the
passwd
command. - If you have disabled SELinux -skip this step. If you have SELinux enabled you MUST do this step
- Before you rebootyou will need to make sure that SELinux allows the file changes. At the prompt ,enter:
touch /.autorelabel
. This will signal SELinux on the next reboot that the filesystem has changed (the changed password) and allow the change to be loaded. This will cause the whole filesystem to be ‘relabeled’ which might take a while, depending on the size of the filesystem and the speed of the machine, so be aware of this possibility.
- Before you rebootyou will need to make sure that SELinux allows the file changes. At the prompt ,enter:
- Type
exit
to leave the chroot environment and enterreboot
.