在打印窗口把「目标」选为「另存为 PDF」即可保存,页面已带 awsgood.com 版权水印。 返回原文

www.awsgood.com

How to Connect to an EC2 Instance Using SSH: Step-by-Step

2026-11-06 AWS Configuration 约 6 分钟

TL;DR

Prerequisites: what SSH into EC2 actually needs

Before typing a single command, confirm these exist:

Requirement How to check
Key pair created (or public key registered) aws ec2 describe-key-pairs --query 'KeyPairs[].KeyName'
Security group inbound TCP 22 from your IP aws ec2 describe-security-groups --group-ids sg-xxx
Instance has a public IPv4 or is reachable via bastion/SSM aws ec2 describe-instances --instance-ids i-xxx --query 'Reservations[].Instances[].PublicIpAddress'
Subnet route table has 0.0.0.0/0 → igw-xxx (for public access) aws ec2 describe-route-tables
OpenSSH client on your laptop ssh -V

Your “current public IP” is whatever your ISP hands you right now — get it fresh, don’t reuse yesterday’s:

MYIP=$(curl -s https://checkip.amazonaws.com)
echo "${MYIP}/32"


## Step-by-step: connect to an EC2 instance using SSH

### 1. Create and store the key pair

```bash
aws ec2 create-key-pair 
  --key-name smb-ops-2024 
  --key-type ed25519 
  --key-format pem 
  --query 'KeyMaterial' 
  --output text > ~/.ssh/smb-ops-2024.pem

chmod 400 ~/.ssh/smb-ops-2024.pem


The key material is returned **once**. If you lose the file you cannot download it again — you re-register a new public key instead (see FAQ).

### 2. Open port 22 to exactly one address

```bash
aws ec2 authorize-security-group-ingress 
  --group-id sg-0123456789abcdef0 
  --protocol tcp --port 22 
  --cidr "${MYIP}/32"


`/32` means one host. `0.0.0.0/0` means the whole internet will be brute-forcing your `sshd` within minutes; it is not a shortcut, it's a countdown.

### 3. Launch the instance with that key (or reuse an existing one)

```bash
aws ec2 run-instances 
  --image-id ami-0abcdef1234567890 
  --instance-type t3.micro 
  --key-name smb-ops-2024 
  --security-group-ids sg-0123456789abcdef0 
  --subnet-id subnet-0123456789abcdef0 
  --associate-public-ip-address 
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=ops-jump}]'


Fetch the address:

```bash
aws ec2 describe-instances 
  --filters "Name=tag:Name,Values=ops-jump" "Name=instance-state-name,Values=running" 
  --query 'Reservations[].Instances[].PublicIpAddress' --output text


### 4. Connect

```bash
ssh -i ~/.ssh/smb-ops-2024.pem ec2-user@203.0.113.10


On the first connection you'll be asked to accept the host fingerprint — verify it against the console's system log if the instance handles anything sensitive.

### 5. Make it repeatable with `~/.ssh/config`

```ini
Host ops-jump
    HostName 203.0.113.10
    User ec2-user
    IdentityFile ~/.ssh/smb-ops-2024.pem
    IdentitiesOnly yes
    ServerAliveInterval 60
    ConnectTimeout 5


Now `ssh ops-jump` is the whole command.

### 6. Private-subnet instance via a jump host

```bash
ssh -J ec2-user@203.0.113.10 ubuntu@10.0.2.15


Or in config: `ProxyJump ops-jump`. This keeps the private instance's security group closed to the internet entirely — the bastion SG is the only thing exposed.

## Key parameters and recommended values

| Parameter | What it does | Recommended value |
|---|---|---|
| AMI user name | The pre-created login on the image | `ec2-user` (Amazon Linux/RHEL), `ubuntu` (Ubuntu), `admin` (Debian), `rocky` (Rocky) |
| `-i` / `IdentityFile` | Private key used for auth | Path under `~/.ssh`, permissions `400` |
| SG inbound TCP 22 source | Who may reach `sshd` | Your IP `/32`, or an SG reference from the bastion only |
| `IdentitiesOnly yes` | Stops the agent offering every key | Always `yes` when a host has multiple keys |
| Key type | Algorithm for the pair | `ed25519`, or `rsa` with 4096 bits for legacy tooling |
| `ConnectTimeout` | Fail fast instead of hanging | `5`–`10` seconds |
| Public IP | Internet reachability | Bastion only; private workloads via SSM or `ProxyJump` |

## How to verify the connection is real and locked down

```bash
# 1. Is the port even reachable?
nc -vz -w 5 203.0.113.10 22

# 2. Is the login working with the right identity?
ssh -v ops-jump 'whoami; hostname; ip -4 addr show | grep inet'

# 3. Is password auth actually off on the host?
ssh ops-jump 'sudo sshd -T | grep -E "^(passwordauthentication|permitrootlogin|pubkeyauthentication)"'


Expected output: `passwordauthentication no`, `permitrootlogin without-password` (or `no`), `pubkeyauthentication yes`. If password auth is on, fix it:

```bash
sudo sed -i 's/^#?PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sshd -t && sudo systemctl reload sshd   # Ubuntu: systemctl reload ssh


`sshd -t` validates the config before reload — never skip it, a syntax error plus a restart can lock you out of a box with no console access.

## Hard-won lesson: "SSH is down" was a security group /32 that aged out

A staging instance went unreachable one morning — `ssh` hung at `Connecting to 203.0.113.10...` with no error for 30 seconds. The instinctive read is "sshd crashed", but two cheap checks reframed it in under a minute: `nc -vz -w 5 <ip> 22` also timed out (so it's network, not the daemon), and `aws ec2 describe-security-groups` showed the only port-22 rule was a `/32` matching the office IP from three weeks earlier. The ISP had rotated the lease over the weekend.

I confirmed it was a block, not a routing fault, using VPC flow logs before touching anything — that mattered because the box also fronted a client API, and I wasn't going to briefly open `0.0.0.0/0` on a hunch:

```bash
aws ec2 describe-flow-logs --filter Name=resource-id,Values=eni-0abc123
# then in CloudWatch Logs Insights on the flow log group:
# fields @timestamp, srcaddr, dstport, action
# | filter dstport = 22 and action = "REJECT"
# | sort @timestamp desc | limit 20


The `REJECT` entries from the new office IP proved the SG was the gate, and the daemon was fine the whole time. Permanent fix: replaced IP-pinned rules with SSM Session Manager for day-to-day access, kept SSH behind a small client VPN, and put a `ConnectTimeout 5` in the config so the next incident fails loudly instead of hanging.

## Security and cost notes

- **SSH itself is free.** What costs money is the plumbing: a bastion instance running 24/7, an Elastic IP, or a NAT Gateway if your private instance needs egress to reach anything. Public IPv4 addressing also carries a charge in most regions now — rates vary by region, so check the EC2 pricing page rather than trusting a blog number.
- Prefer **SSM Session Manager** for routine access: no inbound port, no key distribution, IAM-audited sessions. It needs the SSM agent and an instance profile with `AmazonSSMManagedInstanceCore`.
- Rotate keys per person, not per team. A shared `.pem` in a Slack channel is how you end up unable to revoke anyone's access.
- Log `sshd` auth failures to CloudWatch (or at least keep them local) — repeated `Invalid user` lines are the cheapest early warning you'll get.
- If you're managing a dozen instances and would rather not track key rotation and security group drift by hand, this is the sort of thing we handle at awsgood.com.

## Common pitfalls

| Symptom | Cause | Fix |
|---|---|---|
| `Permission denied (publickey)` | Wrong AMI user or key not in `~/.ssh/authorized_keys` | Run `ssh -vvv` and check which key was offered; confirm the user name for that AMI |
| Connection hangs, then times out | SG missing your current IP, NACL block, no route to IGW, or no public IP | `nc -vz` + SG check + `describe-route-tables` |
| `WARNING: UNPROTECTED PRIVATE KEY FILE` | Key permissions too open | `chmod 400 ~/.ssh/key.pem` |
| `Too many authentication failures` | Agent offering every loaded key | Add `IdentitiesOnly yes` |
| `Host key verification failed` after a rebuild | New instance reused the old IP | `ssh-keygen -R 203.0.113.10` then reconnect |
| Works from laptop, not from CI | CI has a different egress IP | Add the CI IP range or switch to SSM/Instance Connect |

Sources