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

相关推荐
九狼1 天前
Flutter URL Scheme 跨平台跳转
人工智能·flutter·github
逛逛GitHub1 天前
4 个热门的 GitHub 开源项目
github
程序员鱼皮1 天前
GitHub 关注突破 2w,我总结了 10 个涨星涨粉技巧!
前端·后端·github
HelloGitHub1 天前
《HelloGitHub》第 119 期
开源·github
冬奇Lab2 天前
一天一个开源项目(第35篇):GitHub Store - 跨平台的 GitHub Releases 应用商店
开源·github·资讯
Jahzo2 天前
openclaw桌面端体验--ClawX
人工智能·github
逛逛GitHub2 天前
6个粉丝推荐的 GitHub 项目,收藏一波。
github
MaoPou2 天前
Hello Haxe篇
github