如何同时管理GitLab/GitHub的SSH密钥

如何同时管理多个仓库的SSH公钥(GitLab/GitHub)

开发中遇到要同时使用不同GIT仓库时(如公司的GitLab仓库和自己的GitHub仓库,或两个不同帐号的GitHub仓库),需要配置多个SSH公钥,我整理了配置流程并为不同仓库或项目配置独立的密钥与远程地址。

前置说明

  • 默认密钥目录:~/.ssh/
  • 私钥/公钥命名示例:id_rsa / id_rsa.pub(GitLab),id_rsa_github / id_rsa_github.pub(GitHub)
  • 所有命令在终端中执行;将 "你的邮箱" 替换为你的实际邮箱

一、为 GitLab 生成并配置密钥

  1. 生成 RSA 密钥:

    bash 复制代码
    ssh-keygen -t rsa -b 4096 -C "你的邮箱"
  2. 将私钥加入 ssh-agent(确保 ssh-agent 已启动):

    bash 复制代码
    ssh-add ~/.ssh/id_rsa
  3. 查看并复制公钥,去 GitLab 配置:

    bash 复制代码
    cat ~/.ssh/id_rsa.pub

二、为 GitHub 生成并配置密钥

  1. 生成 RSA 密钥:

    bash 复制代码
    ssh-keygen -t rsa -b 4096 -C "你的邮箱"
  2. 将私钥加入 ssh-agent:

    bash 复制代码
    ssh-add ~/.ssh/id_rsa_github
  3. 查看并复制公钥,去 GitHub 配置:

    bash 复制代码
    cat ~/.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 地址):

    bash 复制代码
    git remote set-url origin git@github.com:用户名/项目.git
  • 按项目名称配置(使用 Host 别名):

    bash 复制代码
    git remote set-url origin github-specific:用户名/项目.git

五、远程地址修改方法

  • 在 IDE(如 IDEA)中:打开项目,菜单 GIT -> Manage Remotes 修改

  • 命令行修改:进入项目目录,执行

    bash 复制代码
    git remote set-url origin <URL>

六、其他

依次类推,如果需要增加更多的仓库,只需重复增加id_rsa_xx和修改config文件步骤即可。

相关推荐
m0_694845576 小时前
tinylisp 是什么?超轻量 Lisp 解释器编译与运行教程
服务器·开发语言·云计算·github·lisp
June`6 小时前
muduo项目排查错误+测试
linux·c++·github·muduo网络库
weixin_6688 小时前
GitHub 2026年AI项目详细数据汇总表-AI分析-分享
人工智能·github
CoderJia程序员甲1 天前
GitHub 热榜项目 - 日榜(2026-02-05)
ai·开源·大模型·github·ai教程
明月心9521 天前
git remote add 用法
gitlab
weixin_6681 天前
GitHub 2026年AI项目热度分析报告-AI分析-分享
人工智能·github
MicrosoftReactor1 天前
技术速递|GitHub Copilot CLI 斜杠命令速查表
github·copilot·cli
wu~9701 天前
GitHub永不遗忘,使用git push -f来覆盖的提交依旧保留
git·github
m0_694845571 天前
music-website 是什么?前后端分离音乐网站部署实战
linux·运维·服务器·云计算·github
独自破碎E1 天前
已经 Push 到远程的提交,如何修改 Commit 信息?
开发语言·github