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

使用Paramiko密钥认证连接AWS EC2失败求助

Troubleshooting Paramiko Key Authentication Failures for AWS EC2

Hey there! Let's work through this issue step by step—since you already know your PEM key works with regular SSH, we can narrow down the problem pretty quickly. Here are the most common fixes and debugging steps tailored for someone new to Paramiko:

1. Double-Check Key Path & Permissions

Even if your key works locally, Paramiko might stumble on path confusion or permission issues (AWS is strict about PEM file permissions!).

  • Use an absolute file path in your code instead of a relative one to avoid any "file not found" surprises. For example:
    from paramiko import SSHClient, AutoAddPolicy, RSAKey
    
    # Replace with your actual full path to the PEM
    key = RSAKey.from_private_key_file('/Users/your-name/.ssh/aws-key.pem', passphrase=None)
    
  • Ensure your PEM file has tight permissions. AWS requires chmod 400 on the key file—even if it works locally, running scripts as a different user or copying files can mess this up. Run this in your terminal:
    chmod 400 /path/to/your-key.pem
    

2. Use the Correct Loading Method & Username

AWS PEM keys are RSA keys, but sometimes mixing up loading methods or using the wrong username causes failures:

  • Try letting Paramiko handle key loading directly via key_filename in the connect method (this avoids manual key parsing errors):
    from paramiko import SSHClient, AutoAddPolicy, SSHException
    
    try:
        ssh = SSHClient()
        ssh.set_missing_host_key_policy(AutoAddPolicy())
        ssh.connect(
            hostname='your-ec2-public-ip',
            username='ec2-user',  # Swap to 'ubuntu' if you're using an Ubuntu AMI!
            key_filename='/absolute/path/to/your-key.pem',
            passphrase=None
        )
        print("Connection successful!")
        ssh.close()
    except SSHException as e:
        print(f"Auth failed: {str(e)}")
    

Critical note: Usernames vary by AMI—Amazon Linux uses ec2-user, Ubuntu uses ubuntu, RHEL uses ec2-user or root.

3. Enable Verbose Logging to Pinpoint the Issue

Paramiko has detailed logging that will tell you exactly where things go wrong. Add this to the top of your script to get debug output:

import logging
logging.basicConfig(level=logging.DEBUG)

You’ll see lines like "Trying key ..." or "Server refused our key"—these clues will tell you if the key isn’t loading, the username is wrong, or the instance is rejecting the connection for another reason.

4. Test with a Minimal Working Script

Sometimes extra code in your script can introduce issues. Start with this stripped-down example to rule out other variables:

from paramiko import SSHClient, AutoAddPolicy

ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy())

try:
    ssh.connect(
        'your-ec2-public-ip',
        username='ec2-user',
        key_filename='/absolute/path/to/your-key.pem'
    )
    # Run a simple command to confirm connection
    stdin, stdout, stderr = ssh.exec_command('echo "Hello from EC2!"')
    print(stdout.read().decode())
    ssh.close()
except Exception as e:
    print(f"Error: {e}")

If you still hit errors after these steps, share the verbose log output and your code snippet—we can dig deeper from there!

内容的提问来源于stack exchange,提问作者kavise

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:13:32