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:
- Login on your AWS console
- Go to EC2 and create a new temporary instance.
- Stop both temporary and old instances.
- Detach the Elastic Block Store (EBS) from the old instance
- Attach the same instance to the temporary instance on /dev/xvdf1 .
- Start the temporary instance.
- You should be able to use the key pair generated to access the server.
- Once accessed via SSH, create a directory and call it anything. Let’s say “oldebs”.
mkdir oldebs
- 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
- 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
- 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
- Save all the changes.
- Stop the temporary instance.
- Detach the EBS from the temporary instance and attach it to the old instance.
- Start the old instance.
- You should be able to use your key pair that was generated when you created your old instance.
- Access the server via SSH.
- Change your root password.
- 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
- You might need to restart SSH.
sudo systemctl restart sshd
- Don’t forget to stop the temporary password to avoid extra charges by AWS.
If you lost the Key Pair:
Coming soon