必须为github和gitlab分别生成独立ssh密钥对,配置~/.ssh/config实现自动路由,并将对应公钥添加至平台,否则会因公钥冲突导致permission denied (publickey)错误。

一台Mac要同时向GitHub个人仓库和GitLab公司仓库推送代码,必须为每个平台生成独立的SSH密钥对,否则会因公钥冲突导致Permission denied (publickey)错误,无法完成git push或git clone操作。
生成两套独立的SSH密钥
打开终端,依次执行以下命令:
先生成GitHub用的密钥:ssh-keygen -t rsa -b 4096 -C "your-github-email@example.com" -f ~/.ssh/id_rsa_github
再生成GitLab用的密钥:ssh-keygen -t rsa -b 4096 -C "your-gitlab-email@company.com" -f ~/.ssh/id_rsa_gitlab
【注意:-f参数后必须指定完整路径和自定义文件名,绝对不能直接回车使用默认id_rsa,否则会覆盖已有密钥】
执行过程中两次输入空密码即可(若设密码,后续每次操作都要输)。
将私钥添加到ssh-agent并持久化
启动ssh-agent后台服务:eval "$(ssh-agent -s)"
把两把私钥都加入agent管理:ssh-add -K ~/.ssh/id_rsa_github && ssh-add -K ~/.ssh/id_rsa_gitlab
这一步让系统记住私钥,避免每次git操作都手动输密码。-K参数会把密码存入macOS钥匙串,下次重启终端仍生效。
配置~/.ssh/config实现自动路由
进入SSH目录:cd ~/.ssh
创建或编辑config文件:touch config && open -e config
在 OpenClaw 中管理 GitHub 仓库、Pull Request、Issue 与工作流。适用于审查 PR、管理 Issue、自动化 GitHub Actions、同步仓库等场景。
在文件中写入以下内容(注意大小写、空格、换行):
# GitHub
# Host是自定义别名,可任意命名,但后续clone时要用这个别名
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
AddKeysToAgent yes
UseKeychain yes
# GitLab
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_rsa_gitlab
AddKeysToAgent yes
UseKeychain yes
保存退出。这个config文件就是路由规则——当你执行git@github.com时,系统自动匹配第一段规则,加载对应私钥;同理git@gitlab.com走第二段。
把公钥分别添加到对应平台
方法一(命令行复制):
复制GitHub公钥:pbcopy 复制GitLab公钥:pbcopy
方法二(手动打开):
在Finder中按Cmd+Shift+G,输入~/.ssh,双击打开id_rsa_github.pub和id_rsa_gitlab.pub两个文件,全选→复制。
登录GitHub → Settings → SSH and GPG keys → New SSH key → 粘贴内容,Title填“Mac-GitHub”;
登录GitLab → Preferences → SSH Keys → 粘贴内容,Title填“Mac-GitLab”。
验证是否配置成功
第一步:测试GitHub连接
ssh -T git@github.com
第二步:测试GitLab连接
ssh -T git@gitlab.com
第三步:确认当前使用的密钥
ssh -T -v git@github.com 2>&1 | grep 'identity file'
看到输出中显示 identity file /Users/xxx/.ssh/id_rsa_github 即表示GitHub走的是正确密钥;同理替换域名可验证GitLab。如果任一命令返回“Hi username! You've successfully authenticated”,说明该平台已通。










