“permission denied (publickey)”错误源于ssh未正确匹配密钥,根本原因是github与gitlab共用git@域名但未通过~/.ssh/config按host精确路由,导致密钥错用;user.email仅影响commit签名,与ssh认证无关。

能,但必须靠 SSH config 文件做路由控制,不是改 Git 配置就能解决的。 否则你 push 到 GitHub 的请求会走 GitLab 的密钥,直接被拒绝。
为什么 git config --global user.email 不影响 SSH 认证
Git 的 user.email 只用于 commit 签名,和服务器认证完全无关。SSH 连接时,Git 客户端根本不会读这个字段——它只看 URL 中的 host 名,再按 ~/.ssh/config 里定义的 Host 规则匹配对应 IdentityFile。
- 错误现象:
git push报错Permission denied (publickey),但ssh -T git@github.com却成功 → 说明密钥本身没问题,只是没被正确选中 - 根本原因:GitHub 和 GitLab 的 remote URL 都是
git@xxx.com结构,若没配config,OpenSSH 默认用~/.ssh/id_rsa,而它很可能只属于其中一个平台 - 关键点:
Host行必须和你 clone 或设置 remote 时用的 host 完全一致(比如git@gitlab.example.com就不能简写成gitlab.example.com)
~/.ssh/config 必须这样写才生效
编辑 ~/.ssh/config,每段开头的 Host 必须是你实际使用的 remote host 名。常见错误是把公司 GitLab 域名写成 gitlab,但你 clone 时用的是 git@gitlab.example.com,那就必须写 Host gitlab.example.com。
- 正确示例:
Host github.com HostName github.com User git IdentityFile ~/.ssh/id_rsa_github Host gitlab.example.com HostName gitlab.example.com User git IdentityFile ~/.ssh/id_rsa_gitlab
User 固定填 git(不是你的邮箱),几乎所有 Git 托管平台都用这个用户名走 SSH-f 指定路径,避免覆盖默认密钥:ssh-keygen -t ed25519 -C "me@github.com" -f ~/.ssh/id_ed25519_github
ssh -T -v git@github.com,输出里看到 debug1: identity file /Users/xxx/.ssh/id_ed25519_github type 3 才算对VSCode 内操作必须用 SSH URL,不能用 HTTPS
VSCode 的 Git 面板、GitLens、克隆弹窗等所有功能,底层调用的都是 Git CLI。如果 remote 是 HTTPS 地址(如 https://github.com/user/repo.git),它根本不会查 ~/.ssh/config,自然无法隔离密钥。
- 检查当前 remote:
git remote get-url origin,如果不是以git@开头,立刻改掉:git remote set-url origin git@github.com:user/repo.git - 克隆新仓库时,在 VSCode 里粘贴 SSH 地址(GitLab 页面点 “Clone” → 切到 SSH 标签再复制)
- 全局替换 HTTPS 为 SSH(仅限 GitLab):
git config --global url."git@gitlab.example.com:".insteadOf "https://gitlab.example.com/",注意末尾冒号和斜杠方向 - VSCode 设置里禁用自动 HTTPS fallback:在
settings.json加"git.allowAuthenticationFallback": false
真正麻烦的不是配 config,而是所有项目 remote URL 都得手动核对一遍——尤其那些老项目,可能十年前就是 HTTPS 克隆的,现在 push 依然走密码弹窗或 token 认证,完全绕过你的 SSH 隔离逻辑。











