惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Vulnerabilities – Threatpost
L
LINUX DO - 热门话题
H
Hacker News: Front Page
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
Lohrmann on Cybersecurity
Cisco Talos Blog
Cisco Talos Blog
O
OpenAI News
S
Securelist
Security Latest
Security Latest
T
Threat Research - Cisco Blogs
H
Heimdal Security Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recorded Future
Recorded Future
Microsoft Azure Blog
Microsoft Azure Blog
MyScale Blog
MyScale Blog
Webroot Blog
Webroot Blog
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
Latest news
Latest news
N
Netflix TechBlog - Medium
N
News and Events Feed by Topic
D
Docker
D
DataBreaches.Net
A
About on SuperTechFans
T
Tor Project blog
V
V2EX
G
Google Developers Blog
博客园 - Franky
N
News | PayPal Newsroom
T
The Blog of Author Tim Ferriss
I
InfoQ
H
Help Net Security
V2EX - 技术
V2EX - 技术
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Security Affairs
SecWiki News
SecWiki News
The Register - Security
The Register - Security
人人都是产品经理
人人都是产品经理
NISL@THU
NISL@THU
小众软件
小众软件
B
Blog
T
Threatpost
P
Palo Alto Networks Blog
博客园 - 【当耐特】
L
LangChain Blog
AWS News Blog
AWS News Blog
月光博客
月光博客
宝玉的分享
宝玉的分享

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
SSH Config File Mastery: Turning `~/.ssh/config` Into a Productivity Tool
Mahafuzur Rahaman · 2026-05-25 · via DEV Community

Stop typing the same long SSH commands every day. One file eliminates the repetition and unlocks features most developers don't know exist.


Here's a test. How do you SSH into your staging server?

If the answer involves typing an IP address, a username, a port number, and a key file path every single time — this article is for you.

The ~/.ssh/config file lets you replace all of that with a single word. But it goes much further than aliases. With the right config, SSH becomes smarter: it automatically selects the right key, routes connections through jump hosts, keeps connections alive, compresses traffic, and handles dozens of edge cases without you thinking about them.

This is a complete guide to the SSH client config file — from the basics to patterns used by senior engineers and DevOps teams.


The Basics: What the Config File Is

~/.ssh/config is a plain text file that configures the behavior of the SSH client. Every time you run ssh, scp, sftp, or rsync over SSH, OpenSSH reads this file and applies the matching configuration.

If the file doesn't exist yet, create it:

mkdir -p ~/.ssh
touch ~/.ssh/config
chmod 600 ~/.ssh/config   # Important: must not be world-readable

The file follows a simple structure:

Host <pattern>
    <Directive> <value>
    <Directive> <value>

Host <pattern>
    <Directive> <value>

Each Host block applies to connections whose target matches the pattern. Patterns support wildcards. A Host * block applies to all connections.

Order matters: SSH reads the file top to bottom and applies the first matching value for each directive. Put specific host blocks before general wildcard blocks.


Part 1: The Essentials — Stop Typing Long Commands

Basic Host Alias

Before:

ssh -i ~/.ssh/id_ed25519_work -p 2222 ubuntu@203.0.113.50

After, with config:

Host staging
    HostName 203.0.113.50
    User ubuntu
    Port 2222
    IdentityFile ~/.ssh/id_ed25519_work
    IdentitiesOnly yes

Now:

ssh staging

This also works with scp, rsync, and any other SSH-based tool:

scp staging:/var/log/app.log ./
rsync -avz staging:/var/www/html/ ./backup/

Common Directives Reference

Host           Pattern to match against the target name
HostName       Actual hostname or IP to connect to
User           Remote username
Port           Remote port (default: 22)
IdentityFile   Path to private key
IdentitiesOnly Only use the specified key, not the agent
Compression    Enable data compression (yes/no)
ServerAliveInterval  Keepalive ping interval (seconds)
ServerAliveCountMax  Reconnect attempts before giving up
ConnectTimeout       Timeout for initial connection (seconds)


Part 2: Wildcards and Pattern Matching

Config patterns aren't just for exact hostnames. They support glob-style wildcards.

* Matches Anything

Host *.prod.example.com
    User ec2-user
    IdentityFile ~/.ssh/id_ed25519_prod
    ServerAliveInterval 60

This applies to web.prod.example.com, db.prod.example.com, bastion.prod.example.com — any host in that subdomain.

? Matches a Single Character

Host web-?
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519_dev

Matches web-1, web-2, web-a — but not web-10 or web-prod.

Multiple Patterns on One Host

Host web db cache
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519_work

This block matches if the target is web, db, or cache. Useful for hosts that share configuration but are addressed by different names.

Negation With !

Host * !bastion.prod.example.com
    ServerAliveInterval 30

Applies to all hosts except bastion.prod.example.com.


Part 3: Jump Hosts and ProxyJump

This is where the config file starts to feel like magic.

The Problem

Your production servers aren't publicly accessible. You connect through a bastion host:

# Old way: two-step connection
ssh ubuntu@bastion.example.com
# (now on bastion)
ssh ubuntu@db.internal

This is clunky, leaves you with a shell on the bastion, and doesn't work with scp directly.

ProxyJump: The Clean Solution

Host db.internal
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519_prod
    ProxyJump bastion.example.com

Host bastion.example.com
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519_prod

Now ssh db.internal automatically routes through the bastion. Transparent to you, invisible in usage.

Wildcard ProxyJump for an Entire Private Network

Host *.internal
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519_prod
    ProxyJump bastion.example.com

Any *.internal host goes through the bastion automatically. You never have to think about it.

Multi-Hop: Chaining Jump Hosts

Host deep.internal
    ProxyJump bastion.example.com,internal-gateway.example.com

Comma-separated jump hosts are traversed in order. SSH creates the full chain automatically.

ProxyJump vs. ProxyCommand

You may see older configs using ProxyCommand:

# Old way (still works, but verbose)
Host *.internal
    ProxyCommand ssh -W %h:%p bastion.example.com

ProxyJump is cleaner and equivalent. Use ProxyJump for new configs.


Part 4: Identity Management — Right Key, Every Time

Managing multiple SSH keys is one of the most common sources of friction. The config file eliminates it.

Per-Client-Context Keys

# Work infrastructure
Host *.work.example.com
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519_work
    IdentitiesOnly yes

# Client A
Host *.clienta.com
    User deploy
    IdentityFile ~/.ssh/id_ed25519_clienta
    IdentitiesOnly yes

# Personal/GitHub
Host github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_personal
    IdentitiesOnly yes

IdentitiesOnly yes is important. Without it, SSH tries every key in your agent until one works or you hit MaxAuthTries. With it, only the specified key is tried. This prevents authentication failures on servers with low MaxAuthTries settings.

Multiple GitHub/GitLab Accounts

A classic pain point: work and personal GitHub accounts on the same machine.

Host github-personal
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_personal
    IdentitiesOnly yes

Host github-work
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_work
    IdentitiesOnly yes

In your personal repo's git remote, use github-personal instead of github.com:

git remote set-url origin git@github-personal:yourusername/repo.git

In work repos:

git remote set-url origin git@github-work:workorg/repo.git

Each repo automatically uses the right key.


Part 5: Connection Persistence and Performance

ControlMaster: Reuse Existing Connections

By default, every ssh invocation opens a new TCP connection and runs the full handshake. With ControlMaster, subsequent connections to the same host reuse an existing socket.

Host *
    ControlMaster auto
    ControlPath ~/.ssh/sockets/%r@%h:%p
    ControlPersist 4h

Create the socket directory:

mkdir -p ~/.ssh/sockets

Effect: your second ssh staging connects in milliseconds. Your rsync, scp, and ansible runs share the same connection pool. The master connection persists for 4 hours after the last session closes.

This is a significant productivity boost if you frequently open multiple connections to the same hosts.

Keepalive: Stop Connections From Dropping

Idle SSH connections drop when firewalls, NAT, or cloud load balancers close inactive sessions.

Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3

SSH sends a keepalive packet every 60 seconds. If 3 consecutive packets go unanswered, the connection is considered dead. This keeps sessions alive through idle periods and gives clean failure detection.

Compression: Faster on Slow Links

Host remote-dev
    Compression yes

Compression reduces data volume at the cost of CPU. Valuable on slow or high-latency links (cellular, satellite, congested VPN). Generally not worth enabling on fast local/cloud networks.

ConnectTimeout: Fail Fast

Host *
    ConnectTimeout 10

Don't wait the default 2 minutes for a connection to a dead host. Fail in 10 seconds and move on.


Part 6: Environment and Forwarding Options

Agent Forwarding — With Caution

Agent forwarding allows the SSH agent on your local machine to be used on the remote server. This lets you SSH from the remote server to a third server using your local key — without copying private keys to the remote.

Host bastion.example.com
    ForwardAgent yes

Use this carefully. When agent forwarding is enabled, anyone with root on the remote server can use your agent (and thus your keys) for the duration of your connection. Only enable it for hosts you fully trust.

A safer alternative for multi-hop access is ProxyJump, which doesn't expose your agent.

# Prefer this:
Host db.internal
    ProxyJump bastion.example.com

# Over this (when agent forwarding is only needed to reach the next hop):
Host bastion.example.com
    ForwardAgent yes

X11 Forwarding

For running GUI applications over SSH:

Host dev-gui
    ForwardX11 yes
    ForwardX11Trusted no

ForwardX11Trusted no is safer — it limits what the remote application can do with your X display. Use yes only if you need it.

Environment Variables

Pass local environment variables to the remote session:

Host dev
    SendEnv LANG LC_* EDITOR

The server must have AcceptEnv configured to accept these variables in sshd_config.


Part 7: Real-World Config Patterns

The Team Bastion Setup

# Bastion — the entry point to production
Host bastion
    HostName bastion.prod.example.com
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519_prod
    IdentitiesOnly yes
    ServerAliveInterval 60
    ControlMaster auto
    ControlPath ~/.ssh/sockets/%r@%h:%p
    ControlPersist 2h

# All internal prod hosts through bastion
Host *.prod.internal
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519_prod
    IdentitiesOnly yes
    ProxyJump bastion

# Dev servers — more relaxed settings
Host *.dev.example.com
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519_dev
    IdentitiesOnly yes
    ServerAliveInterval 30
    StrictHostKeyChecking accept-new

The Developer Workstation

# GitHub — personal
Host github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_github
    IdentitiesOnly yes

# Work GitLab
Host gitlab.work.example.com
    User git
    IdentityFile ~/.ssh/id_ed25519_work
    IdentitiesOnly yes

# Local VMs
Host homelab
    HostName 192.168.1.100
    User ubuntu
    StrictHostKeyChecking accept-new
    UserKnownHostsFile ~/.ssh/known_hosts_local

# Default settings for everything
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3
    ConnectTimeout 10
    ControlMaster auto
    ControlPath ~/.ssh/sockets/%r@%h:%p
    ControlPersist 1h
    HashKnownHosts yes
    IdentitiesOnly yes

The CI/CD Pipeline Config

CI environments often need SSH config too. Write it dynamically during pipeline setup:

mkdir -p ~/.ssh && chmod 700 ~/.ssh

cat >> ~/.ssh/config << EOF
Host deploy-target
    HostName $DEPLOY_HOST
    User deploy
    IdentityFile ~/.ssh/deploy_key
    IdentitiesOnly yes
    StrictHostKeyChecking accept-new
    ConnectTimeout 15
EOF

chmod 600 ~/.ssh/config
echo "$DEPLOY_PRIVATE_KEY" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key


Part 8: Debugging Config Issues

Test What Config Will Be Applied

ssh -G staging

-G prints the full resolved configuration for staging without connecting. Shows exactly which options are active, where they came from, and what key will be used.

Verbose Mode

ssh -v staging    # Basic debug
ssh -vv staging   # More verbose
ssh -vvv staging  # Maximum verbosity

Look for lines like:

debug1: Reading configuration data /home/user/.ssh/config
debug1: /home/user/.ssh/config line 5: Applying options for staging
debug1: Trying private key: /home/user/.ssh/id_ed25519_work

This tells you exactly which config block matched and which key is being tried.

Check File Permissions

SSH is strict about config file permissions. If permissions are wrong, SSH ignores the file:

chmod 600 ~/.ssh/config
chmod 700 ~/.ssh/
chmod 600 ~/.ssh/id_*          # Private keys
chmod 644 ~/.ssh/id_*.pub      # Public keys
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/known_hosts

Common Issues

Symptom Likely Cause Fix
Config ignored entirely Wrong file permissions chmod 600 ~/.ssh/config
Wrong key being used Missing IdentitiesOnly yes Add to host block
ProxyJump failing Bastion block misconfigured Test bastion connection first
ControlMaster errors Socket directory missing mkdir -p ~/.ssh/sockets
Options not applying Wrong host pattern Run ssh -G hostname to debug

The Config File as Living Documentation

One underappreciated use of ~/.ssh/config: it's documentation.

A well-structured config file tells the story of your infrastructure. Which hosts exist. How they're accessed. Which environments use which keys. What's behind a bastion.

Keep it in version control (your dotfiles repo, your team's infrastructure repo). Comment it. Update it when infrastructure changes. It's a low-overhead way to maintain institutional knowledge about how your systems are connected.

# Production infrastructure
# Bastion: bastion.prod.example.com
# Last updated: 2024-01
# Key rotation: annually (next: 2025-01)

Host bastion
    ...


Quick Reference: Most Useful Directives

Host                    Pattern matching target hostname
HostName                Actual address to connect to
User                    Remote username
Port                    Remote port
IdentityFile            Path to private key
IdentitiesOnly          Only try specified keys (yes/no)
ProxyJump               Jump host(s), comma-separated
ForwardAgent            Forward local SSH agent (yes/no)
ServerAliveInterval     Keepalive interval in seconds
ServerAliveCountMax     Keepalive failure threshold
ControlMaster           Connection sharing (auto/yes/no)
ControlPath             Socket path for shared connections
ControlPersist          How long to keep master alive
Compression             Enable compression (yes/no)
ConnectTimeout          Initial connection timeout (seconds)
StrictHostKeyChecking   Host key policy (yes/accept-new/no)
HashKnownHosts          Hash known_hosts entries (yes/no)
LogLevel                Verbosity (QUIET/INFO/VERBOSE/DEBUG)


The Bottom Line

The SSH config file is one of those tools that pays compounding dividends. You invest 30 minutes setting it up properly, and every SSH-related task for the rest of your career gets a little faster, a little less error-prone, and a little more automatic.

Start with your most-used hosts. Add Host * defaults for keepalives and connection sharing. Wire up your jump hosts. Handle your multiple GitHub accounts. In an hour, you'll have a config that feels like it was built for exactly your workflow — because it was.

# The one command to start:
ssh -G any-host-you-connect-to
# See what's currently configured, then improve from there.


Follow for more practical SSH, infrastructure, and developer productivity content.