每次 SSH 连接都要输入一长串参数?~/.ssh/config 配置文件可以简化连接命令,还能统一管理多个主机的配置。

配置文件位置

SSH 客户端配置按以下顺序读取(后读取的优先级更高):

  1. /etc/ssh/ssh_config — 系统全局配置
  2. ~/.ssh/config — 用户个人配置

用户配置会覆盖全局配置中的同名选项。

基本语法

配置文件由多个 Host 块组成,每个块定义一组主机的配置:

1
2
3
4
5
6
Host 别名
    选项1 值1
    选项2 值2

Host 另一个别名
    选项1 值1

注意:每行的缩进使用空格(通常 4 个空格或 1 个 Tab),不是必须但推荐。

常用配置选项

选项 说明 示例
HostName 实际主机名或 IP HostName 192.168.1.100
User 登录用户名 User admin
Port SSH 端口 Port 2222
IdentityFile 指定私钥文件 IdentityFile ~/.ssh/id_ed25519
PreferredAuthentications 首选认证方式 PreferredAuthentications publickey
ServerAliveInterval 心跳间隔秒数 ServerAliveInterval 60
ServerAliveCountMax 心跳失败次数上限 ServerAliveCountMax 3
ProxyJump 跳板机 ProxyJump bastion

实战示例

简化连接命令

不使用配置文件:

1
ssh -p 2222 -i ~/.ssh/id_ed25519 admin@192.168.1.100

配置文件:

1
2
3
4
5
Host myserver
    HostName 192.168.1.100
    User admin
    Port 2222
    IdentityFile ~/.ssh/id_ed25519

使用配置后:

1
ssh myserver

通配符配置

使用 * 匹配所有主机,设置全局默认值:

1
2
3
4
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3
    HashKnownHosts yes

重要:通配符配置应放在文件末尾,因为 SSH 使用第一个匹配的值。

多主机配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# 生产服务器组
Host prod-*
    User deploy
    IdentityFile ~/.ssh/prod_key

Host prod-web-01
    HostName 10.0.1.10

Host prod-db-01
    HostName 10.0.1.20
    Port 2222

# 开发服务器组
Host dev-*
    User developer
    IdentityFile ~/.ssh/dev_key

Host dev-sandbox
    HostName 192.168.10.100

连接时:

1
2
ssh prod-web-01    # 使用 deploy 用户和 prod_key
ssh dev-sandbox    # 使用 developer 用户和 dev_key

跳板机配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Host bastion
    HostName jump.example.com
    User jumpuser
    IdentityFile ~/.ssh/bastion_key

Host internal-*
    ProxyJump bastion
    User admin
    IdentityFile ~/.ssh/internal_key

Host internal-web
    HostName 10.0.2.10

Host internal-db
    HostName 10.0.2.20

连接内网服务器:

1
ssh internal-web

SSH 会自动先连接跳板机,再跳转到目标主机。

查看生效配置

使用 -G 选项查看指定主机的完整配置:

1
ssh -G myserver

输出示例(部分):

1
2
3
4
5
6
host myserver
user admin
hostname 192.168.1.100
port 2222
identityfile ~/.ssh/id_ed25519
serveraliveinterval 60

这有助于调试配置是否生效。

配置优先级

SSH 配置值的优先级(从高到低):

  1. 命令行选项(-o-p 等)
  2. 用户配置文件 ~/.ssh/config
  3. 系统配置文件 /etc/ssh/ssh_config
  4. 内置默认值

命令行选项优先级最高,可用于临时覆盖配置文件中的值:

1
2
# 配置文件中 User 是 admin,临时用 root 登录
ssh -o User=root myserver

安全建议

  1. 限制文件权限
1
chmod 600 ~/.ssh/config
  1. 使用 HashKnownHosts
1
2
Host *
    HashKnownHosts yes

这会将 ~/.ssh/known_hosts 中的主机名哈希化,防止泄露连接过的主机列表。

  1. 指定认证方式
1
2
3
Host myserver
    PreferredAuthentications publickey
    PasswordAuthentication no

强制使用公钥认证,避免密码尝试。

参考