使用Paramiko密钥认证连接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 400on 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_filenamein theconnectmethod (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

