AWSJunior
EC2 SSH: Permission denied (publickey) and unprotected key file
Permission denied (publickey) means the server refused your key. Check the username for the AMI, the right .pem file, its 0400 permissions and the .ssh modes.
What you see
Permission denied (publickey).Host key not found in [directory]Connection closed by [instance] port 22WARNING: UNPROTECTED PRIVATE KEY FILE!followed byPermissions 0777 for '.ssh/my_private_key.pem' are too open.
What it means
You reached the instance, but authentication failed. Three things cause nearly all of it: the wrong username for the AMI, the wrong private key, or key file permissions that are too open, in which case SSH ignores the key.
How to confirm the cause
- 1Run SSH with maximum detail
ssh -vvv -i /path/key-pair-name.pem USER@ec2-203-0-113-25.compute-1.amazonaws.com
A key the server does not accept ends with
Permission denied (publickey). - 2Check which key pair the instance was launched with
aws ec2 describe-instances --instance-ids INSTANCE_ID --query 'Reservations[].Instances[].KeyName'
Causes and fixes
Wrong username for the AMI
- HOW TO TELL
- Connecting as the wrong user.
- FIX
- Use the default user for the image: Amazon Linux
ec2-user, Ubuntuubuntu, Debianadmin, RHELec2-userorroot, SUSEec2-userorroot, Rocky Linuxrocky, Bitnamibitnami. For other images check with the AMI provider.
Private key file is too open
- HOW TO TELL
- The
UNPROTECTED PRIVATE KEY FILEwarning, or the key is silently ignored. - FIX
- Make the key readable only by you.
chmod 0400 .ssh/my_private_key.pem
Wrong key pair
- HOW TO TELL
- The key name on the instance differs from the
.pemyou are using. - FIX
- Use the file that matches the key pair shown for the instance. If you generated your own key, it must be RSA; DSA keys are not accepted.
Permissions changed on the instance
- HOW TO TELL
- It used to work and nothing else is wrong.
- FIX
authorized_keysmust be limited to the owner. Stop the instance, attach its root volume to a temporary instance in the same Availability Zone, and fix the modes, then reattach the volume.chmod 600 MOUNT/home/USER/.ssh/authorized_keys chmod 700 MOUNT/home/USER/.ssh chmod 700 MOUNT/home/USER
How to stop it coming back
- Store the
.pemwith 0400 from the day you download it. - Document the default user per image your team uses.
- Keep a break-glass path, such as Session Manager, so a lost key is not an outage.
Keep going
- Runbook: EC2 SSH: Connection timed out
- Runbook: Compute Engine SSH: connection timed out, refused or publickey denied
- Runbook: Azure Linux VM: SSH connection failed or refused
- Cheat sheet: SSH
- Cheat sheet: Linux Permissions
- Lesson: the linux topic in Learn
Sources
AWS documentation (docs.aws.amazon.com), read 18 Nov 2026.