SSH 客户端配置文件(~/.ssh/config)的语法结构清晰简洁,主要由 Host 匹配块配置指令 组成。

1. 基本语法结构

1
2
3
Host 别名/匹配模式
指令 值
指令 值
  • Host 行:定义匹配条件,可以是一个别名、主机名或通配符模式
  • 配置行:以 Key Value 形式书写,缩进(空格或 Tab)表示属于上方 Host
  • 注释:以 # 开头

2. 常用配置指令

指令 说明 示例
HostName 真实主机地址(IP 或域名) HostName 192.168.1.100
User 登录用户名 User ubuntu
Port SSH 端口(默认 22) Port 2222
IdentityFile 私钥路径 IdentityFile ~/.ssh/id_rsa
ProxyJump 跳板机/堡垒机 ProxyJump jump-serveruser@jump:22
ForwardAgent 开启 Agent 转发 ForwardAgent yes
LocalForward 本地端口转发 LocalForward 8080 localhost:80
RemoteForward 远程端口转发 RemoteForward 9090 localhost:3000
ServerAliveInterval 心跳检测间隔(秒) ServerAliveInterval 60
StrictHostKeyChecking 是否严格检查主机密钥 StrictHostKeyChecking no
IdentitiesOnly 仅使用指定密钥 IdentitiesOnly yes
AddKeysToAgent 自动将密钥加入 ssh-agent AddKeysToAgent yes

3. 通配符匹配

Host 支持使用通配符实现批量配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 匹配所有 .github.com 子域名
Host *.github.com
User git
IdentityFile ~/.ssh/github_key

# 匹配所有以 lab- 开头的主机
Host lab-*
User student
StrictHostKeyChecking no

# 匹配所有主机(全局默认值,通常放文件末尾)
Host *
ServerAliveInterval 60
ServerAliveCountMax 3

4. 完整示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 公司跳板机
Host jump
HostName jump.company.com
User admin
Port 2222
IdentityFile ~/.ssh/jump_key

# 通过跳板机连接内网服务器
Host web-server
HostName 10.0.1.50
User ubuntu
IdentityFile ~/.ssh/internal_key
ProxyJump jump
LocalForward 3306 localhost:3306 # 转发 MySQL 端口

# GitHub 专用配置
Host github.com
User git
IdentityFile ~/.ssh/github_ed25519
IdentitiesOnly yes

# 实验室服务器群组
Host lab-01 lab-02 lab-03
HostName %h.university.edu.cn # %h 会被替换为实际匹配的名称
User researcher
ServerAliveInterval 30

5. 特殊变量

在配置值中可使用以下占位符:

  • %h:被替换为 Host 行匹配的主机名
  • %u:本地用户名
  • %p:端口
  • %r:远程用户名

6. 配置继承规则

  • 配置文件从上到下解析,第一个匹配的 Host 块生效
  • 若多个 Host 模式都匹配,先定义的优先
  • 使用 Host * 放在末尾可设置全局默认值
1
2
3
4
5
6
Host server*      # 先检查这个
User admin

Host * # 后备默认值
User ubuntu
Port 22

当连接 server01 时,User 为 admin;连接其他主机时,User 为 ubuntu

7. 文件权限要求

配置文件对权限敏感:

  • ~/.ssh/config 权限应为 600chmod 600 ~/.ssh/config
  • 私钥文件权限应为 600

如需查看系统级默认配置,可查阅 /etc/ssh/ssh_config(语法相同)。