无法通过SSH访问AWS实例,遇公钥认证报错求助
Hey there, I’ve dealt with this exact SSH issue on EC2 instances before— let’s break down what’s going wrong and how to fix it step by step:
First, Fix Your Command Syntax & File Mismatch
Looking at the command you ran, there are two obvious issues that are probably causing the failure:
chmod 400 virtue.pem ssh -i "file.pem" ubuntu@ec2-publicIp.us-west-2.compute.amazonaws.com
- You’re combining two separate commands into one line. Run the
chmodcommand alone first to set strict permissions (AWS requires this for PEM files):chmod 400 virtue.pem - There’s a critical file name mismatch: you used
virtue.pemin thechmodcommand butfile.pemin the SSH command. Make sure your SSH command uses the same key file you just updated permissions for:ssh -i "virtue.pem" ubuntu@ec2-54-214-97-39.us-west-2.compute.amazonaws.com
Verify Your Key Pair Is Linked to the EC2 Instance
Even with a corrected command, if your key pair isn’t associated with the instance, you’ll still hit this error:
- Log into the AWS EC2 Console, find your instance, and check the Key pair name under the "Details" tab.
- Confirm this matches the key pair that generated your
virtue.pemfile. If they don’t match:- Use the correct PEM file for the key pair linked to the instance, or
- Use AWS Systems Manager Session Manager to connect to the instance, then add your public key (generate it with
ssh-keygen -y -f virtue.pem) to the~/.ssh/authorized_keysfile of theubuntuuser.
Double-Check the Instance’s SSH Configuration
If your key is correct, verify the instance’s SSH daemon is set up to accept public keys properly:
- Connect via Session Manager (since SSH is failing) and open the SSH config file:
sudo nano /etc/ssh/sshd_config - Ensure these lines are enabled and set correctly:
PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2 - Save the file and restart the SSH service:
sudo systemctl restart sshd - Also, check that the
~/.ssh/authorized_keysfile for theubuntuuser has your correct public key, and set its permissions to600if needed:chmod 600 ~/.ssh/authorized_keys
Quick Sanity Check: Security Groups & NACLs
While the error points to authentication, it’s worth confirming your instance’s security group allows inbound SSH (port 22) from your IP address, and that your VPC’s Network ACLs allow both inbound and outbound traffic on port 22.
内容的提问来源于stack exchange,提问作者Hemendra singh

