How to reset the root password in RHEL7/CentOS7/Scientific Linux 7- based systems

Objective

Resetting the root password in RHEL7/CentOS7/Scientific Linux 7

Requirements

RHEL7 / CentOS7 / Scientific Linux 7

Difficulty

MODERATE

Instructions

Things have changed in the RHEL7 world and so has the preferred way of resetting the root password. Although the old way of interrupting the boot process (init=/bin/bash) still works, it is no longer bulletproof and recommended.
‘Systemd’ uses ‘rd.break’ to interrupt the boot. Let’s have a quick walk through the whole procedure.

Boot into the minimal mode

Reboot the system and press e while being on the kernel list page, before the autoboot starts the system automatically. You get into the edit mode.

Interrupt the boot process

In the kernel string – at the end of the line starting linux 16 /vmlinuz- ect type rd.break. Then Ctrl+X to reboot.
The system boots into the initial ram drive and it’s mounted on /sysroot
In this mode you are not required to type the password.

Remount the system so that it can read and write

 switch_root:/# mount -o remount,rw /sysroot/

Make /sysroot your root

 switch_root:/# chroot /sysroot

The command line will change slightly.



Change the root password

sh-4.2# passwd

Load SELinux policy

sh-4.2# load_policy -i

Set context type on /etc/shadow file

sh-4.2# chcon -t shadow_t /etc/shadow

Note:
You could bypass the last 2 steps by creating an autorelabel file instead, but autorelabeling might take a long time.

sh-4.2# touch /.autorelabel

For that reason, and despite it is easier, it should be regarded as the ‘lazy option’, and is not recommended.

Exit & reboot

Exit & reboot and log in with your new root password.