如何同时管理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文件步骤即可。

相关推荐
AuTumn-L7 小时前
使用 SSH 密钥认证实现安全免密登录
服务器·安全·ssh
领创工作室7 小时前
GitHub Workflows 全面解析:从核心概念到开源实现
运维·github
一条泥憨鱼10 小时前
【从0开始学习计算机网络】| DNS -记录类型详解
计算机网络·http·github·域名·dns·记录
u13013010 小时前
GitHub 热榜项目:日榜(2026-08-21)
驱动开发·github
MicrosoftReactor12 小时前
技术速递|GitHub Copilot App 入门指南:管理你的工作
ai·github·copilot·agent
阿里嘎多学长14 小时前
2026-08-20 GitHub 热点项目精选
开发语言·程序员·github·代码托管
小妖同学学AI14 小时前
AI视频生成难在提示词?这个Claude插件让Seedance 2.0效率翻倍,附超全示例!
人工智能·开源·github·音视频
zhixingheyi_tian15 小时前
Linux 之 ssh
linux·服务器·ssh
草莓熊Lotso16 小时前
【Linux网络加餐】手动部署:SSH 与 Web 服务实战 + 底层原理全解析
linux·运维·网络·人工智能·python·langchain·ssh