多个 SSH key 可以同时存在并精确到“谁在自己的工作目录里用自己的 key”。
几种实用做法(任选其一或组合):
做法一:按仓库设置专用私钥(最直接)
- 在每个仓库里绑定要用的 key:
- 生成你的 key:ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_you -C “you@example.com”
- 公钥加到你自己的 GitLab 账号
- 在仓库根目录执行:
- git config core.sshCommand “ssh -i ~/.ssh/id_ed25519_you -o IdentitiesOnly=yes”
- git config user.name ” 你的名字 ”
- git config user.email ” 你的邮箱 ”
- 优点:只影响当前仓库;不同目录(你/他)可各用各的 key。
- 验证:ssh -T git@gitlab.example.com 会显示你的账号(从该仓库执行 Git 命令时由 core.sshCommand 生效)
做法二:用 ~/.ssh/config 定义主机别名,再改远端 URL(常用)
- 配置主机别名(每人一把钥匙):
# ~/.ssh/config
Host gitlab-you
HostName gitlab.example.com
User git
IdentityFile ~/.ssh/id_ed25519_you
IdentitiesOnly yes
Host gitlab-other
HostName gitlab.example.com
User git
IdentityFile ~/.ssh/id_ed25519_other
IdentitiesOnly yes
- 你的仓库用你的别名:
- git remote set-url origin git@gitlab-you:group/repo.git
- 对方在 TA 的目录把远端设成 git@gitlab-other:group/repo.git
- 测试身份:
- ssh -T git@gitlab-you
做法三:按“工作目录前缀”自动应用(全局配置里分目录)
- 适合“我的所有仓库都在 ~/work/me/,同事在 ~/work/other/”这种布局。
- 全局 gitconfig 增加条件包含:
# ~/.gitconfig
[includeIf "gitdir:~/work/me/"]
path = ~/.gitconfig-me
[includeIf "gitdir:~/work/other/"]
path = ~/.gitconfig-other
- 在各自的附加文件里指定 key 和用户信息:
# ~/.gitconfig-me
[user]
name = 你的名字
email = you@example.com
[core]
sshCommand = ssh -i ~/.ssh/id_ed25519_you -o IdentitiesOnly=yes
(同理为 ~/.gitconfig-other 配置对方的 key)
做法四:按会话使用专属 ssh-agent(一次性或临时)
- 仅在你的 shell 会话中加载你的钥匙:
eval "$(ssh-agent -s)"
ssh-add -D
ssh-add ~/.ssh/id_ed25519_you
ssh -T git@gitlab.example.com
- 或单次命令临时指定:
GIT_SSH_COMMAND='ssh -i ~/.ssh/id_ed25519_you -o IdentitiesOnly=yes' git push
注意事项
- IdentitiesOnly yes 很重要,可避免 ssh-agent 里“随机挑错钥匙”。
- 公钥必须添加到各自的 GitLab 账号;同一把私钥不要共用。
- 如果两个人用的是同一个系统账号,强烈建议用“做法一或三”把配置限定到仓库/目录,避免互相影响。
- 验证当前用谁身份:ssh -T git@你的 GitLab 域名;查看远端:git remote -v。