git-ssh并与gitlab共存

==作者:cybsky==

在本地已有 GitLab SSH 密钥的情况下,可以通过以下步骤实现 GitHub 和 GitLab 的 SSH 密钥共存:


1. 生成 GitHub 专用密钥

1
ssh-keygen -t rsa -b 4096 -C "your_github_email@example.com" -f ~/.ssh/id_rsa_github
  • -f ~/.ssh/id_rsa_github:指定新密钥的文件名,避免覆盖原有密钥。
  • 输入时直接回车使用默认路径,或自定义路径。

2. 添加密钥到 SSH Agent

1
2
3
4
5
6
7
8
# 启动 SSH Agent(如果未运行)
eval "$(ssh-agent -s)"

# 添加 GitLab 默认密钥(如果尚未添加)
ssh-add ~/.ssh/id_rsa

# 添加 GitHub 新密钥
ssh-add ~/.ssh/id_rsa_github

3. 配置 SSH Config 文件

编辑 ~/.ssh/config 文件,设置不同 Host 对应不同密钥:

1
2
3
4
5
6
7
8
9
10
11
# GitLab 配置(假设使用默认域名)
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_rsa

# GitHub 配置
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github

注意

  • 如果使用自托管的 GitLab 实例,需将 gitlab.com 替换为实际域名(如 gitlab.mycompany.com)。

  • 每个 Host 块需独立配置。

    image-20250618110830763


4. 验证配置

1
2
3
4
5
# 测试 GitHub 连接
ssh -T git@github.com

# 测试 GitLab 连接
ssh -T git@gitlab.com
  • 成功时会显示欢迎信息(如 Hi username! You've successfully authenticated...)。
文章作者: CYBSKY
文章链接: https://cybsky.top/2025/06/18/cyb-mds/git/git-ssh并与gitlab共存/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 CYBSKY