How to Regain SSH Access After Losing Your Private Key

DONT FORGET TO REPLACE ME LATER

You will perform two main phases:

  1. Preparation (On your computer): Create a new key pair.
  2. Recovery (In AWS): Use the browser-based terminal to log in and install your new key.

The main idea is to use the EC2 Instance Connect (browser-based SSH) as a temporary “backdoor” to install a new, permanent key.


Step 1: Create a New Key Pair (Locally)

First, you need to create a new key pair on your own computer. This will generate a new private key (which you keep secret) and a new public key (which you will give to EC2).

  1. Open a terminal on your local computer.
  2. Use the ssh-keygen command to create a new key. ssh-keygen -t -f ~/Downloads/my-new-ec2-key
    • This creates two files in your Downloads folder:
      • my-new-ec2-key.pem (The private key. Keep this safe!)
      • my-new-ec2-key.pub (The public key. This is what you’ll add to the instance.)
  3. Open the public key file (my-new-ec2-key.pub) with a text editor and copy its entire contents to your clipboard. It will look something like ssh-rsa AAAAB3NzaC1yc....

Step 2: Connect to Your Instance Using a Browser

Next, you’ll use the AWS Console to get temporary access to the instance’s terminal.

  1. Log in to your AWS Console.
  2. Navigate to EC2 > Instances.
  3. Select the instance you lost the key for.
  4. Click the Connect button.
  5. Select the EC2 Instance Connect tab. (Do not choose “SSH client”).
  6. Keep the default username (e.g., ec2-user, ubuntu) and click Connect.
  7. A new browser window will open with a command-line terminal for your instance.

Step 3: Add Your New Public Key to the Instance

Now you are inside the instance. You just need to “authorize” the new public key you created in Step 1.

  1. In the browser terminal, you need to edit the authorized_keys file. This file lists all public keys that are allowed to log in.
  2. Use a text editor like nano or vi to open the file. (Nano is easier if you’re not familiar with Vi).Bashnano ~/.ssh/authorized_keys
  3. Scroll to the very bottom of the file.
  4. Paste your new public key (the one from my-new-ec2-key.pub that you copied to your clipboard).
  5. Save the file and exit.
    • In nano: Press Ctrl+O to Write (Save), press Enter to confirm the filename, and press Ctrl+X to Exit.

Step 4: Verify the New Key

You’re done with the browser. The final step is to test your new key from your local computer’s terminal.

  1. Close the browser terminal.
  2. Open a new local terminal on your computer.
  3. Important: Before you can use your new private key, you must set its permissions so only you can read it.Bashchmod 400 ~/Downloads/my-new-ec2-key
  4. Now, try to SSH into your instance using your new private key.Bashssh -i "~/Downloads/my-new-ec2-key" ec2-user@<your-instance-ip-or-dns>
  5. If everything worked, you will log in successfully. You have now regained access to your instance.