You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法通过SSH访问AWS实例,遇公钥认证报错求助

Fixing "Connection blocked because server only allows public key authentication" for AWS EC2

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 chmod command 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.pem in the chmod command but file.pem in 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.pem file. If they don’t match:
    1. Use the correct PEM file for the key pair linked to the instance, or
    2. 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_keys file of the ubuntu user.

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_keys file for the ubuntu user has your correct public key, and set its permissions to 600 if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:08:58