Linux怎么配置Git使用SSH多密钥:Linux下多账号仓库管理详解

作者:袖梨 2026-06-10
Git clone 提示 Permission denied (publickey)是因为 SSH 未按预期使用指定密钥,根本原因是 ~/.ssh/config 配置未生效:Host 必须为自定义别名、HostName 填真实域名、IdentityFile 用绝对路径、User git 不可省略、remote URL 必须改为对应 Host 别名,且 config 文件权限需为600。

为什么 git clone 总提示 Permission denied (publickey)

因为 SSH 客户端根本没用你配的第二把密钥——它默认只试 ~/.ssh/id_rsa,而 [email protected] 这种 URL 不会触发任何路由逻辑。Git 本身不读 SSH 密钥,它只调用 ssh 命令;真正决定用哪把密钥的是 ~/.ssh/config 文件里的 Host 规则,但前提是 Git 的 remote URL 必须匹配那个 Host 名。

常见错误现象:

  • 明明生成了 id_ed25519_workssh -T [email protected] 却仍走 id_rsa
  • 配置了 Host github-work,但 remote 还是 [email protected]:user/repo.git,结果完全没生效
  • ssh-add -l 显示多把密钥已加载,但 Git 推送仍失败

怎么写对 ~/.ssh/config 才能生效

这个文件不是“可选配置”,而是多密钥路由的唯一开关。必须满足三个硬性条件,缺一不可:

  • Host 行必须是自定义别名(如 github-personal),不能和真实域名一样;HostName 才填真实域名(如 github.com
  • IdentityFile 必须写绝对路径:/home/you/.ssh/id_ed25519_personal~ 在 config 里不展开
  • 每组配置之间必须空一行,且不能有缩进或中文标点

正确示例:

Host github-personal  HostName github.com  User git  IdentityFile /home/you/.ssh/id_ed25519_personalHost github-work  HostName github.com  User git  IdentityFile /home/you/.ssh/id_ed25519_work

错误点:漏掉 User git(GitHub/GitLab 都强制要求该用户)、用 ~/.ssh/... 而非完整路径、把 Host 写成 github.com-personal 却没改 remote URL。

remote URL 必须手动改成 Host 别名

这是最容易被跳过的一步。配置完 ~/.ssh/config 后,所有已有仓库的 remote 都得重设,否则旧 URL 依然直连,完全绕过你的路由规则。

  • 查看当前 remote:git remote get-url origin
  • 改成对应 Host 别名:git remote set-url origin git@github-personal:me/repo.git
  • 新克隆必须用别名:git clone git@github-work:company/project.git,而不是 [email protected]:...

注意:ssh -T git@github-personal 是验证 config 是否生效的唯一可靠方式;ssh -T [email protected] 永远只会走默认密钥,不能用来测试多账号。

不同平台(GitHub/GitLab/Gitee)要分开 Host 块

一个 Host 块只能绑定一个 HostName。如果你同时用 GitHub 个人号、GitLab 公司号、Gitee 团队号,就得写三组互不干扰的配置:

  • GitHub 用 Host github-personalHostName github.com
  • GitLab 用 Host gitlab-companyHostName gitlab.com
  • Gitee 用 Host gitee-teamHostName gitee.com

不要试图在一个块里写多个 HostName,SSH 不支持。也不要让不同平台共用同一把私钥——平台侧可能校验邮箱或限制密钥复用,导致某一方拒绝登录。

权限和路径问题比想象中更常出错:~/.ssh/config 必须是 600 权限,IdentityFile 私钥也必须是 600,否则 SSH 直接忽略该条配置。用 chmod 600 ~/.ssh/config ~/.ssh/id_* 快速修正。

相关文章

精彩推荐