如何同时管理多个仓库的SSH公钥(GitLab/GitHub)
开发中遇到要同时使用不同GIT仓库时(如公司的GitLab仓库和自己的GitHub仓库,或两个不同帐号的GitHub仓库),需要配置多个SSH公钥,我整理了配置流程并为不同仓库或项目配置独立的密钥与远程地址。
前置说明
- 默认密钥目录:
~/.ssh/ - 私钥/公钥命名示例:
id_rsa/id_rsa.pub(GitLab),id_rsa_github/id_rsa_github.pub(GitHub) - 所有命令在终端中执行;将
"你的邮箱"替换为你的实际邮箱
一、为 GitLab 生成并配置密钥
-
生成 RSA 密钥:
bashssh-keygen -t rsa -b 4096 -C "你的邮箱" -
将私钥加入 ssh-agent(确保 ssh-agent 已启动):
bashssh-add ~/.ssh/id_rsa -
查看并复制公钥,去 GitLab 配置:
bashcat ~/.ssh/id_rsa.pub
二、为 GitHub 生成并配置密钥
-
生成 RSA 密钥:
bashssh-keygen -t rsa -b 4096 -C "你的邮箱" -
将私钥加入 ssh-agent:
bashssh-add ~/.ssh/id_rsa_github -
查看并复制公钥,去 GitHub 配置:
bashcat ~/.ssh/id_rsa_github.pub
三、配置 ~/.ssh/config
使用 SSH 配置文件为不同仓库或项目指定不同密钥。
方式一:按仓库地址配置(推荐)
当远程地址使用标准域名时,自动匹配对应密钥:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
IdentitiesOnly yes
方式二:按项目名称配置(使用 Host 别名)
为某项目使用自定义 Host 别名:
Host github-specific
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
IdentitiesOnly yes
四、修改项目远程仓库地址
根据上面的两种配置方式,项目中的 origin 远程可以这样设置:
-
按仓库地址配置(标准 SSH 地址):
bashgit remote set-url origin git@github.com:用户名/项目.git -
按项目名称配置(使用 Host 别名):
bashgit remote set-url origin github-specific:用户名/项目.git
五、远程地址修改方法
-
在 IDE(如 IDEA)中:打开项目,菜单
GIT -> Manage Remotes修改 -
命令行修改:进入项目目录,执行
bashgit remote set-url origin <URL>
六、其他
依次类推,如果需要增加更多的仓库,只需重复增加id_rsa_xx和修改config文件步骤即可。