Troubleshooting “Permission Denied (Publickey)” When Connecting to AWS EC2 via SSH
Encountering a “Permission denied (publickey)” message when trying to SSH into your AWS EC2 instance can be frustrating. However, this is a common issue with a straightforward resolution. Whether you’re running Ubuntu or another Linux distribution on your EC2 instance, ensuring proper key permissions and user settings will help you connect successfully.
Key Considerations for SSH Access
-
Correct Key Permissions: Before anything else, ensure your private key file has the correct permissions. SSH requires that your key file is not accessible to others. Use the
chmod
command to set the file permissions appropriately:chmod 600 ec2-keypair.pem
This command sets your key file to be readable and writable only by you. SSH will refuse to use the key if the permissions are too open for security reasons.
-
Identify the Correct User: Depending on the AMI (Amazon Machine Image) used, the default SSH user may differ. Here’s a general guideline for some common AMIs:
- Amazon Linux and Amazon Linux 2: Use
ec2-user
- RHEL: Use
ec2-user
orroot
- Ubuntu: Use
ubuntu
- CentOS: Use
centos
- Fedora: Use
fedora
- SUSE: Use
ec2-user
orroot
When you attempt to SSH, specify the user like so:
ssh -i ec2-keypair.pem ubuntu@your-ec2-instance-public-dns
- Amazon Linux and Amazon Linux 2: Use
-
Ensure Your Instance’s Security Group Allows SSH: Verify that the security group associated with your EC2 instance allows SSH access. By default, SSH uses port 22. Check your inbound rule in your security group configuration on the AWS Management Console:
-
Head to the EC2 console.
-
Select the relevant instance and navigate to its security group.
-
Ensure there’s an inbound rule that opens port 22 for your IP address.
It’s best practice to restrict SSH access to specific IP addresses that you control rather than opening it to the entire world.
-
-
Use the Correct DNS or IP Address: Ensure that you’re using the correct public DNS or IP address for your instance. You can find this in the EC2 dashboard under instance details.
Additional Troubleshooting Steps
-
Public Key Installed Properly: Ensure the public key was correctly added to the instance upon creation. You can verify this by checking the
~/.ssh/authorized_keys
file on the EC2 instance—if you have console access or another trusted way to connect. -
SSH Debugging: Run SSH with the
-v
flag for verbose output, providing insights into where the connection fails.ssh -v -i ec2-keypair.pem ubuntu@your-ec2-instance-public-dns
This output will show step-by-step which part of the authentication process is failing.
By following these steps, you should be able to troubleshoot and resolve common issues when connecting to your AWS EC2 instance through SSH. Securely managing your key files and ensuring the correct configurations will save you time and reduce security risks.