I Forgot my Root Password or Lost my Key Pair

How to Create and Reset Key Pair in Ubuntu: A Step-by-Step Guide

If you are completely locked out of Ubuntu by losing your key pair or root password, do not panic. there is a way to reset your key pair or root password.

Follow these steps to be able to gain access again. These steps should work on any Linux but it was only tested on Ubuntu on AWS from my side.

If you lost the root password:

  1. Login on your AWS console
  2. Go to EC2 and create a new temporary instance.
  3. Stop both temporary and old instances.
  4. Detach the Elastic Block Store (EBS) from the old instance
  5. Attach the same instance to the temporary instance on  /dev/xvdf1 .
  6. Start the temporary instance.
  7. You should be able to use the key pair generated to access the server.
  8. Once accessed via SSH, create a directory and call it anything. Let’s say “oldebs”.
    mkdir oldebs
  9. Locate the attached EBS
    sudo lsblk

    Should look something like this

    NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
    loop0         7:0    0 97.7M  1 loop /snap/core/10126
    loop1         7:1    0 97.1M  1 loop /snap/core/9993
    loop2         7:2    0 28.1M  1 loop /snap/amazon-ssm-agent/2012
    nvme1n1     259:0    0 69.9G  0 disk
    nvme0n1     259:1    0   64G  0 disk
    └─nvme0n1p1 259:2    0   64G  0 part /

    The last line should be your attached drive

  10. Mount the EBS that was attached to the new directory (oldebs).
    mount /dev/xvdf1 oldebs

    You might need to access root before doing that

    sudo su
  11. Edit the ssh config file to enable access via key pair and disable access via root password.
    vi /etc/ssh/sshd_config

    And set the following

    PermitRootLogin yes
    PubkeyAuthentication yes
    PasswordAuthentication no
  12. Save all the changes.
  13. Stop the temporary instance.
  14. Detach the EBS from the temporary instance and attach it to the old instance.
  15. Start the old instance.
  16. You should be able to use your key pair that was generated when you created your old instance.
  17. Access the server via SSH.
  18. Change your root password.
  19. Disable key pair access and enable root password access for the SSH config file.
    vi /etc/ssh/sshd_config

    And set the following

    PermitRootLogin yes
    PubkeyAuthentication no
    PasswordAuthentication yes
  20. You might need to restart SSH.
    sudo systemctl restart sshd
  21. Don’t forget to stop the temporary password to avoid extra charges by AWS.

If you lost the Key Pair:

Coming soon

Leave a Comment