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

如何永久存储.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:

Step 1: Securely Store Your PEM Key

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 .ssh folder in your user home directory, create it first:
    mkdir -p ~/.ssh
    
  • Move your .pem file into this directory. Replace /path/to/your/key.pem with 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
    
Step 2: Configure SSH Config for Easy Access

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, then Ctrl+X to exit.
  • Lock down the config file permissions too (SSH likes this for security):
    chmod 600 ~/.ssh/config
    
Step 3: Test Your Setup

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.

Quick Notes for Windows Users
  • WSL Users: Follow the exact steps above—WSL behaves just like a Linux system here.
  • Native Windows (PowerShell/Command Prompt):
    1. Move your .pem file to C:\Users\YourUsername\.ssh (create the folder if it doesn't exist).
    2. Create a config file in that same directory with the same structure as above (use paths like C:\Users\YourUsername\.ssh\key.pem or ~/.ssh/key.pem—OpenSSH on Windows understands both).
    3. Right-click the .pem and config files, go to Properties > Security > Advanced, make sure only your user account has read/write access (remove any other groups/users from the permissions list).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:14:30