Immediate Fix
The most common cause for the “Permission denied (publickey)” error is incorrect file permissions on your private key (.pem) file. SSH requires that your private key is not accessible by other users on your system.
Run the following command to restrict permissions to the file owner only:
chmod 400 your-key-pair.pem
Next, ensure you are using the correct default username for your AMI. Using the wrong username (e.g., using “root” instead of “ec2-user”) will trigger this error.
| AMI Distribution | Default Username |
|---|---|
| Amazon Linux 2 / 2023 | ec2-user |
| Ubuntu | ubuntu |
| CentOS | centos |
| Debian | admin |
| RHEL | ec2-user |
Verify your connection string matches this format:
ssh -i "your-key-pair.pem" ec2-user@your-instance-public-dns
Technical Explanation
When you attempt to connect via SSH, the client offers a public key derived from your private key file. The EC2 instance compares this against the keys stored in the ~/.ssh/authorized_keys file.
The error “Permission denied (publickey)” occurs when the server rejects all offered keys. This happens if the public key on the instance doesn’t match your local private key, or if the server-side permissions are too open.
AWS EC2 instances have a setting called StrictModes enabled by default in the SSH daemon. If the /home/username/ or ~/.ssh/ directories have write permissions for groups or others, the daemon will refuse to read the authorized_keys file for security reasons.

Alternative Methods
If you have lost access to the instance or the keys are corrupted, use the EC2 Instance Connect service. This allows you to push a temporary public key to the instance via the AWS Management Console.
Using AWS Systems Manager (SSM)
If the SSM Agent is installed and the instance has the AmazonSSMManagedInstanceCore IAM role, you can bypass SSH entirely. Use the Session Manager to open a shell directly in your browser.
# Connect via AWS CLI using SSM
aws ssm start-session --target i-0123456789abcdef0
The User Data Script Fix
If you are locked out, you can stop the instance and add a script to the “User Data” field. This script can reset permissions or add a new public key to the authorized_keys file upon the next boot.
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
runcmd:
- chown ec2-user:ec2-user /home/ec2-user/.ssh/authorized_keys
- chmod 600 /home/ec2-user/.ssh/authorized_keys
--//--