CentOS/RHEL change password hash from command line

The problem:

There is a CentOS 5 or RedHat 4 (perhaps versions below or above also) installation with a root password I don't know. I forgot or I simply don't know it, and there are no other accounts on this machine.

Theoretical solution:

I have to write the /etc/shadow file, but I have to write my new password somehow hashed into this file without having any other CentOS like system installed for encoding passwords. I have to boot from some other linux dist and write the file from that environment.

 

Solution:

  • boot up the machine from a bootable linux liveCD (Ubuntu is the most user friendly for me)
  • generate a password hash with the following command with a chosen mypassword
    echo "mypassword" | makepasswd --clearfrom=- --crypt-md5 |awk '{ print $2 }'
  • copy the output string to the clipboard
  • find the root partition of your HDD (or virtual disk if it is a virtual machine) with
    fdisk -l
    command from command line
  • mount the previously found partition to /mnt with the following command
    mount /dev/sda1 /mnt
  • edit the shadow file with the
    gedit /mnt/etc/shadow
    if you are not familiar with VI
  • comment out the current root line like
    root:$1$...
    and insert a new line with exactly the same as the commented was, but change the password hash (beginning with "$1$") to the new one.
  • save the file
  • reboot