Git 本身不支持自动路由密钥,依赖 ~/.ssh/config 实现域名到私钥的映射;需为各平台生成独立密钥并严格配置 Host、HostName、IdentityFile 和 IdentitiesOnly,确保 remote URL 与 Host 一致。

直接靠 Git 本身做不到自动路由密钥——Git 不管理 SSH 密钥,它完全依赖底层 SSH 客户端的行为。真正起作用的是 ~/.ssh/config 文件,它决定了「连哪个域名时用哪把私钥」。
生成专属密钥对
为每个平台单独生成密钥,避免重名覆盖,默认密钥(如 id_rsa)只留一把会引发冲突。
- GitHub 个人账号(推荐 ed25519):
ssh-keygen -t ed25519 -C "me@github.com" -f ~/.ssh/id_ed25519_github - 公司 GitLab(兼容性优先):
ssh-keygen -t rsa -b 4096 -C "me@company.com" -f ~/.ssh/id_rsa_company
生成后,确保 ~/.ssh/ 目录下存在对应私钥(无 .pub 后缀)和公钥(.pub 后缀),私钥权限应为 600(chmod 600 ~/.ssh/id_*)。
配置 ~/.ssh/config 实现域名路由
这个文件是核心开关。每段 Host 配置定义一个「别名 → 实际域名 + 密钥」的映射关系。注意:Host 名必须与 git remote URL 中 @ 后面的部分完全一致。
生成周报:读取本机 Git 仓库最近一周的提交记录,按项目分类提炼总结,生成标准周报格式,通过微信推送并返回给用户。触发词:周报、weekly report、git总结、提交记录总结、工作周报。
- 用编辑器打开或新建:
nano ~/.ssh/config - 添加如下内容(按实际域名和路径调整):
# GitHub 个人 Host github.com HostName github.com User git IdentityFile ~/.ssh/id_ed25519_github IdentitiesOnly yes <h1>公司 GitLab</h1><p>Host git.company.com HostName git.company.com User git IdentityFile ~/.ssh/id_rsa_company IdentitiesOnly yes
IdentitiesOnly yes 是关键项,防止 SSH 尝试其他密钥导致认证失败或误登。
验证并使用
配置完不需重启任何服务,立即生效。但要注意 remote URL 必须匹配 Host 名。
- 测试连接:
ssh -T git@github.com(应显示 Hi xxx!)
ssh -T git@git.company.com(应返回欢迎信息或认证成功提示) - 克隆或设置 remote 时,URL 中的主机部分必须与 config 中的 Host 一致:
✅ 正确:git clone git@github.com:user/repo.git
✅ 正确:git clone git@git.company.com:group/project.git
❌ 错误:用 https 地址、或自定义别名(如 github-personal)却未在 config 中定义该 Host
已有仓库可更新 remote:
git remote set-url origin git@github.com:user/repo.git


















