0

I accidentally deleted the Home directory with sudo rm -r ~, when I try reconnecting the ssh returns

ssh -v key.pem ec2-user@PublicIP-address

ec2-user@PublicIP-address: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

I doubled checked everything, correct IP correct key.

I have also tried clearing my ssh-key -D I have also tried making my own ssh-keygen and add into the ssh-add I have also tried rebooting my remote computer All of these leads to the same outcome

I can still connect the instance via the amazon web console, however I wont be able to do commands such as scp anymore which is crucial for managing my site. At this point I noticed that the Ec2 console shows [~bash4.2] on the commandline input.

Next i tried recreating the home folder by:

sudo mkdir /home/user
cp -rT /etc/skel/ "$HOME"
chown -R ec2-user:ec2-user /home/ec2-user

rebooted the instance and tried again

I still get the same Permission Denied error however now the Ec2 console shows [ec2-user@PrivateIPaddress] on the commandline input which is an indicative I did something right. I am suspicious this might be related to permission conflict due to manually created HOME directory

But the reason I am here is clearly because I am stumped, I can see related question but never answers to this specific problem and I am asking for help. Thanks

Polaroid
  • 1
  • 2

2 Answers2

1

When you logged into your EC2 instance and executed the 'sudo rm' command, you removed the home directory for the logged in user. In this case, that user is ec2-user

As you have access to the EC2 console via the web console, you need to recreate your home directory

mkdir -p /home/ec2-user/.ssh

You now have the home directory - what you dont have is the public key for the ec2-user in the ~/.ssh/authorized_keys file

If you have the private/public key pair that was created with your instance, you could use that but assuming that all is lost, on your home computer, create a new key pair (ssh-keygen -t rsa -b 2048) and copy the contents of the id_rsa.pub file to the EC2 instance (/home/ec2-user/.ssh/authorized_keys)

Make sure that the permissions of the .ssh directory are restrictive

chmod 0700 /home/ec2-user/.ssh
chown -R ec2-user:ec2-user /home/ec2-user

You should now be able to ssh from your external machine into your EC2 host

0

The problem is you by deleting your home directory you delete also .ssh directory where is located your public key for ssh connection. So you should create this directory:

mkdir ~/.ssh
chmod 700 ~/.ssh

And copy there your public key (from backup):

cat public_key_backup >>~/.ssh/authorized_keys
Romeo Ninov
  • 5,263
  • 4
  • 20
  • 26