Reset Linux Server Password Using Rescue Mode

Are you locked out of your Linux server? Have you forgotten your password or lost your access key? Worry not; there is a way to reset the root password and regain access to your server. Keep reading to learn how to reset your Linux server password using rescue mode on your cloud provider.

Your cloud provider may have a different Rescue OS available for use, which will have a small footprint and can boot quickly. Check out the provider’s documentation for more details on how to use their Rescue OS.

Reset root password

Once you are in rescue mode, you can check the attached disks with fdisk -l or lsblk -f. This will display your disk partitions, allowing you to note down the root partition.

When running lsblk on my server, I got the following.

NAME  MAJ:MIN RM  SIZE RO TYPE MOUNTPOINTS
loop0   7:0    0   45M  1 loop /snap/certbot/3462
loop1   7:1    0   45M  1 loop /snap/certbot/3566
loop3   7:3    0 63.5M  1 loop /snap/core20/2015
loop4   7:4    0 40.8M  1 loop /snap/snapd/20092
loop5   7:5    0 40.9M  1 loop /snap/snapd/20290
loop6   7:6    0 63.9M  1 loop /snap/core20/2105
sda     8:0    0 24.5G  0 disk /
sdb     8:16   0  512M  0 disk [SWAP]

Here sda is the root partition that will be mounted.

Once you know the drive to mount, use the following command to mount it.

mount /dev/sda1 /mnt/

It will be locked for writing; we can chroot it to make it writable.

chroot /mnt

The next step is to reset the root password with:

passwd

Enter your newly desired password when prompted.

You can now exit the shell and reboot your server to use the main drive instead of the Rescue drive.

Disable key authentication

If you have enabled key-based access to your server, you will need to disable it for now and access it with a password first. Once confirmed that you can access your server, you can create a new key and upload it to your server to use.

To do this, you should still be in Rescue mode and chroot to the mounted drive. Open the sshd_config file for editing.

vim /etc/ssh/sshd_config

Change:

PasswordAuthentication no

To:

PasswordAuthentication yes

Save and reboot your server. To disable password-based login, set it to no again.

If you are using another user for key-based login, you can set PermitRootLogin to no. Don’t forget to restart SSH afterwards.