Solve - AWS SSH Permission denied (PublicKey) Error

avatar

Borislav Hadzhiev

Sat Sep 25 20212 min read

banner

Photo by Kalen Emsley

Solving AWS SSH Permission denied (PublicKey) Error #

There are 2 main reasons the "Permission denied (publickey)" error occurs when trying to SSH into an AWS EC2 instance:

  1. The username in the ssh connection url is incorrect. The username is different for the different Amazon Machine Images.
  2. The permissions of the private key are incorrect.

permission denied publickey

To solve the "Permission denied (publickey)" error when trying to SSH into an EC2 instance:

  1. Open your terminal in the directory where your private key is located and change its permissions to only be readable by the current user
shell
chmod 600 ec2-private-key.pem
  1. In the AWS EC2 console, click on checkbox next to your instance's name, then click on Actions and select Connect. Click on the SSH client tab and copy the ssh command example.

ssh command example

The example above uses an Amazon Linux AMI, therefore the username isec2-user. However the connection string in the example is not always correct. If you are launching an ubuntu instance the username will be ubuntu, for bitnami instances it is bitnami.

An easy way for find the username for your AMI is to try to log in as root and read the error message:

shell
ssh -i "ec2-private-key.pem" root@YOUR_EC2_PUBLIC_DNS

try login as root

The error message shows the correct username we should be specifying when trying to ssh into the EC2 instance - in this case ec2-user.

Therefore our ssh command should look like:

shell
ssh -i "ec2-private-key.pem" ec2-user@YOUR_EC2_PUBLIC_DNS

Once I updated the username to be ec2-user the connection was established successfully:

corrected username

If you are still getting the error even after correcting the username, run the ssh command in verbose mode:

shell
ssh -v -i "ec2-private-key.pem" ec2-user@YOUR_EC2_PUBLIC_DNS

The -v flag, stands for verbose and logs the ssh command's output to the terminal and is very helpful for debugging.

Make sure your terminal is opened in the directory where your ec2-private-key.pem file is located, otherwise you might get a permission denied error, because the file could not be found.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee