How to Recover Lost root Password in CentOS/RHEL 7
Recovering the** root** password is a trivial task while still logged in as an administrator or a user with full sudo access, but is slightly more involved when an administrator is not logged in. In the latter situation, the administrator could boot from a Live CD, mount the root ﬁle system from there, and edit /etc/shadow. Administrators should also be able to perform root password recovery without the use of external media.
NOTE: On CentOS/RHEL 6 and earlier, an administrator could boot the system into runlevel 1, and be presented with a root prompt. The closest analogs to runlevel 1 on a CentOS/RHEL 7 machine are the rescue.targetand emergency.target targets, both of which require the root password to log in.
On CentOS/RHEL 7, 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. While this is mostly meant for debugging, it can also be used to recover a lost root **password:
1. Reboot the system. Interrupt the boot loader countdown by pressing any key.
2. Move the cursor to the entry that needs to be booted.
3. Press e to edit the selected entry. Move the cursor to the kernel command line (the line that starts with linux16.
4. Append rd.break (this will break just before control is handed from the initramfs to the actual system).
5. Press Ctrl+x to boot with the changes.
At this point, a **root **shell will be presented, with the root ﬁle system for the actual system mounted read-only on /sysroot.
**IMPORTANT **SELinux is not yet enabled at this point, so any new ﬁles being created will not have an SELinux context assigned to them. Keep in mind that some tools (such as passwd) ﬁrst create a new ﬁle, then move it in place of the ﬁle they are intended to edit, effectively creating a new ﬁle without an SELinux context
To recover 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 ﬁle system tree.
# switch_root:/# chroot /sysroot
3. Set a new root password
# sh-4.2# passwd root
4. Make sure that all unlabeled ﬁles (including /etc/shadow at this point) get relabeled during boot.
# sh-4.2# touch /.autorelabel
5. Type exit twice. The ﬁrst will exit the chroot jail, and the second will exit the initramfs debug shell.
At this point, the system will continue booting, perform a full SELinux relabel, then reboot again.