Immediate Fix: Solve SSH Permission Denied (publickey)
The “Permission denied (publickey)” error usually occurs due to incorrect file permissions on your private key or using the wrong username for the AMI.
First, ensure your private key (.pem file) has the correct restricted permissions. SSH will reject keys that are too “open” to other users on your local machine.
chmod 400 your-key-pair.pem
Second, verify you are using the correct default username for your instance. Use the table below to find the correct login for your operating system.
| AMI Type | Default SSH Username |
|---|---|
| Amazon Linux 2 / 2023 | ec2-user |
| Ubuntu | ubuntu |
| Debian | admin |
| RHEL / CentOS | ec2-user |
| SUSE | ec2-user or root |
Verify the Connection String
Ensure you are explicitly pointing to the key file in your SSH command. A common mistake is relying on the default SSH agent without loading the key.
ssh -i "your-key-pair.pem" [email protected]
Technical Explanation
SSH authentication works via a challenge-response mechanism. Your local machine holds the private key, while the AWS EC2 instance holds the matching public key in the ~/.ssh/authorized_keys file.
The “publickey” error triggers when the server evaluates your request and finds no matching authorized key. This happens if the key pair used during instance creation does not match your local .pem file.
Another common cause is the SSH daemon (sshd) configuration on the server. If the permissions on the .ssh/ directory or authorized_keys file on the EC2 instance are too permissive, the server will ignore them for security reasons.

Alternative Methods
If you have lost access to the original key pair or the permissions are corrupted, you can regain access using these AWS-native tools.
Method 1: EC2 Instance Connect
If your AMI supports it (like Amazon Linux 2), use the EC2 Instance Connect browser-based terminal. This bypasses the need for a local SSH client and manually managed keys.
Method 2: AWS Systems Manager (SSM)
If the SSM Agent is installed and the instance has an IAM role with the AmazonSSMManagedInstanceCore policy, you can use “Session Manager” to open a shell without SSH keys.
Method 3: User Data Script
You can replace a lost key by stopping the instance and adding a “User Data” script. This script manually injects a new public key into the authorized_keys file during the next boot cycle.
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
users:
- name: ec2-user
ssh_authorized_keys:
- ssh-rsa AAAAB3Nza...YourNewPublicKey...