如何永久存储.pem密钥,SSH连接AWS EC2无需指定密钥文件?
Hey there! I totally get the annoyance of typing that long key path every time you SSH into your EC2 instance. Let's fix this so you can connect with just a simple command. Here's how to do it properly across different systems:
First, we need to get your key into the standard SSH directory and lock down its permissions—this is critical because SSH will reject keys that have overly open permissions (like being readable by other users on your system).
- If you don't already have a
.sshfolder in your user home directory, create it first:mkdir -p ~/.ssh - Move your
.pemfile into this directory. Replace/path/to/your/key.pemwith the actual path to your file:mv /path/to/your/key.pem ~/.ssh/ - Set the correct file permissions (read/write only for your user):
chmod 600 ~/.ssh/key.pem
Next, we'll set up an SSH config file so you can use a custom alias (like my-ec2) instead of typing the full IP, username, and key path every time.
- Open (or create) the SSH config file:
nano ~/.ssh/config - Paste in the following configuration, replacing the placeholders with your EC2 instance details:
Host my-ec2 # This is your custom alias—name it whatever you want HostName 1.2.3.4 # Replace with your EC2 public IP or DNS name User ec2-user # Note: Default user varies by AMI—Ubuntu uses "ubuntu", Amazon Linux uses "ec2-user" IdentityFile ~/.ssh/key.pem # Path to your stored key - Save and exit the editor: Press
Ctrl+O, hit Enter to confirm, thenCtrl+Xto exit. - Lock down the config file permissions too (SSH likes this for security):
chmod 600 ~/.ssh/config
Now you're ready to connect without specifying the key path! Just run:
ssh my-ec2
If everything works, you'll be logged into your EC2 instance immediately.
- WSL Users: Follow the exact steps above—WSL behaves just like a Linux system here.
- Native Windows (PowerShell/Command Prompt):
- Move your
.pemfile toC:\Users\YourUsername\.ssh(create the folder if it doesn't exist). - Create a
configfile in that same directory with the same structure as above (use paths likeC:\Users\YourUsername\.ssh\key.pemor~/.ssh/key.pem—OpenSSH on Windows understands both). - Right-click the
.pemandconfigfiles, go to Properties > Security > Advanced, make sure only your user account has read/write access (remove any other groups/users from the permissions list).
- Move your
内容的提问来源于stack exchange,提问作者David Alsh

