Reset root password in CentOS 7

In CentOS 6, it used to be possible to reset the root password in single-user mode.  For version 7 of its OS, Red Hat (and therefore CentOS) now requires the root password for access to single-user mode and also to emergency mode.  Therefore, you must access the system before the root filesystem, which contains the authentication details, has been properly mounted.

 

Step 1 – reboot the server

 

Step 2 – Press e in the GRUB2 boot screen to edit the GRUB2 command line

 

Step 3 – find the line that loads the kernel – this line generally begins with “linux16” or “linuxefi”

 

Step 4 – Remove the parameters “rhgb” and “quiet” from this line and, at the end of the line, add the string “rd.break enforcing=0”

 

Step 5 – Press Ctrl X and the system will boot with the edited parameters.  If the root filesystem is encrypted, a password prompt will appear if you press the backspace key.  You can then enter the password to enable temporary, read-only mounting of the root filesystem. It will be mounted as “/sysroot/”.

 

Step 6 – You must remount the root filesystem in read-write mode before you can make any changes to configuration details such as passwords.  This is done with the following command:

#mount -o remount,rw /sysroot

 

Step 7 – You should now set your environment to the filesystem mounted on /sysroot, so that all commands pertain to that filesystem and its files:

#chroot /sysroot/

 

Step 8 – Now, issue the “passwd” command and follow instructions to change the root password:

#passwd

 

Step 9 – Still within the chroot environment, remount your root filesystem as read-only.  Then exit the chroot environment:

#mount -o remount,ro /
#exit

 

Step 10 – Continue the boot process with another “exit” command (if the root filesystem is encrypted, you will again, after issuing “exit”, need to press backspace and enter the password to decrypt it).

 

Step 11 – Do not reboot the system at this point, or you will again be locked out (on rebooting, SELinux will detect that the password file /etc/shadow has been changed and will restrict access to it).  Instead, you must first restore the SELinux labels on that file:

#restorecon /etc/shadow

 

Step 12 – Finally, reboot the system.  After rebooting, you will be able to login with the root password that you set in Step 8.

#reboot