Remis Haroon - رامز
Remis Haroon - رامز

Reputation: 3572

Amazon EC2: How to restore ~/.ssh/authorized_keys file?

I accidentally overwrote the entries in .ssh/authorized_keys. Now I am no longer able to connect to my EC2 instance using my .pem file. I tried to generate a new .pem file, hoping that process will add entries to .ssh/authorized_keys, but it didn't. I tried to read the documentation, but it is slightly confusing for me. Someone who can give a simplified explanation/instructions on this is much appreciated.

Unfortunately, there are no active ssh sessions.. :(

Upvotes: 3

Views: 2802

Answers (2)

Artur INTECH
Artur INTECH

Reputation: 7296

  1. Generate a new key using ssh-keygen -t rsa
  2. Upload your new public key (Network & Security > Import key pair)
  3. Connect to your instance using web-based client EC2 Instance Connect (AWS console home > Instances > Your instance > Connect to instance > EC2 Instance Connect). No key is required for this!
  4. Go to your home directory. /home/ubuntu, for example.
  5. Run mkdir -m 700 /home/ubuntu/.ssh
  6. Copy-paste your public key using nano /home/ubuntu/.ssh/authorized_keys
  7. Run mkdir -m 600 .ssh/authorized_keys

Now you should be able to connect using your public ip address using ssh -i path_to_your_private_key ubuntu@public-ip.

More details: https://repost.aws/knowledge-center/ec2-linux-fix-permission-denied-errors

Upvotes: 0

Christopher
Christopher

Reputation: 44244

If the instance is EBS-based, you can do the following:

  1. Get a correct copy of the authorized_keys file ready. Get it off another one of your instances, or reconstruct it from whole cloth, or grab it off a snapshot, or use a new pem file, or whatever.

  2. Stop the instance you can't reach (do not terminate it). This step is unavoidable. If you can't stop the instance because it's running something important, you're SOL.

  3. Detach the root volume from the stopped instance. It should be something like /dev/sda1. Be sure to give it a name so you can find it in your volume list.

  4. Attach it to a different instance at another mount point, say /dev/sdp.

  5. Mount the volume into a tmpdir on that instance. Say with mkdir /tmp/myrootvol && mount /dev/xvdp /tmp/myrootvol. Note the device name will vary based on your version of Linux (if you're using Linux at all). Much older versions will use different nomenclature.

  6. At this point, you've got a filesystem, a root volume, mounted at /tmp/myrootvol. Fix the authorized_keys file, then unmount the device, and detach the volume.

  7. Reattach the volume to the original instance at /dev/sda1 or whatever device name it was originally attached at.

  8. Start that instance back up.

There you go. You'll have an accessible EC2 instance. But wow that was a pain wasn't it?

Upvotes: 8

Related Questions