如何管理多台服务器的 SSH 配置?
有很多台服务器需要管理,每次输入用户名、IP、端口、密钥很麻烦,想统一管理
解决方案
使用 ~/.ssh/config 统一管理(推荐) 推荐
# ~/.ssh/config # === 通用配置 === Host * ServerAliveInterval 60 ServerAliveCountMax 3 AddKeysToAgent yes ControlMaster auto ControlPath ~/.ssh/sockets/%r@%h-%p ControlPersist 600 # === 生产环境 === Host prod-web HostName 10.0.1.10 User deploy IdentityFile ~/.ssh/prod_key ProxyJump bastion-prod Host prod-db HostName 10.0.1.20 User dba IdentityFile ~/.ssh/prod_key ProxyJump bastion-prod Host bastion-prod HostName bastion.prod.example.com User jump IdentityFile ~/.ssh/prod_key # === 测试环境 === Host test-* User admin IdentityFile ~/.ssh/test_key ProxyJump bastion-test Host test-web HostName 172.16.0.10 Host test-api HostName 172.16.0.11 Host bastion-test HostName bastion.test.example.com User jump IdentityFile ~/.ssh/test_key
将所有服务器信息集中在 config 文件中,使用 Host 别名简化连接。通配符 Host test-* 可以为一组服务器设置共同配置。配合 ControlMaster 实现连接复用加速。
适用场景:管理 5 台以上服务器,需要不同密钥和跳板机配置
为不同项目/环境使用独立密钥
# 为每个环境生成独立密钥 ssh-keygen -t ed25519 -f ~/.ssh/prod_key -C "prod@company" ssh-keygen -t ed25519 -f ~/.ssh/test_key -C "test@company" ssh-keygen -t ed25519 -f ~/.ssh/github_key -C "dev@company" # 在 config 中为不同 Host 指定不同密钥 Host prod-* IdentityFile ~/.ssh/prod_key Host test-* IdentityFile ~/.ssh/test_key Host github.com IdentityFile ~/.ssh/github_key User git
不同环境使用独立密钥,一个密钥泄露不会影响其他环境。也方便按环境吊销和轮换密钥。
适用场景:安全要求较高,需要隔离不同环境的访问权限
使用 Include 拆分配置文件
# ~/.ssh/config(主配置) Include config.d/* Host * ServerAliveInterval 60 AddKeysToAgent yes # ~/.ssh/config.d/work(工作配置) Host work-* User deploy IdentityFile ~/.ssh/work_key Host work-prod HostName prod.work.com # ~/.ssh/config.d/personal(个人配置) Host personal-* User admin IdentityFile ~/.ssh/personal_key Host personal-blog HostName blog.example.com
OpenSSH 7.3+ 支持 Include 指令,可以将配置拆分到多个文件中管理。适合配置量大或需要区分工作/个人的场景。
适用场景:配置文件过长,或需要在工作和个人配置间切换
注意事项
config 文件权限必须为 600,目录权限为 700
Host 匹配从上到下,第一个匹配生效,通用配置(Host *)放最后
Include 指令必须放在文件最前面才能正确加载