本地同时配置 GitHub 和 Gitee 远程仓库(相同邮箱)

本地同时配置 GitHub 和 Gitee 远程仓库(相同邮箱)


配置原理

即使 GitHub 和 Gitee 使用相同邮箱,也能通过以下方式实现本地多平台推送:

  1. 为不同平台生成独立的 SSH 密钥对。
  2. 通过 ~/.ssh/config 文件指定不同平台的密钥路径。
  3. Git 提交邮箱与 SSH 密钥邮箱独立管理。

步骤详解

1. 生成不同的 SSH 密钥对

# 生成 GitHub 密钥(邮箱可相同)
ssh-keygen -t rsa -f ~/.ssh/id_rsa_github -C "your-email@example.com"

# 生成 Gitee 密钥(邮箱可相同)
ssh-keygen -t rsa -f ~/.ssh/id_rsa_gitee -C "your-email@example.com"

说明

  • 执行命令后按回车跳过密码设置(除非需要加密密钥)。
  • 生成文件:
    • GitHub: id_rsa_github(私钥)和 id_rsa_github.pub(公钥)
    • Gitee: id_rsa_gitee(私钥)和 id_rsa_gitee.pub(公钥)

2. 配置 SSH Agent(可选)

# 启动 SSH Agent
eval "$(ssh-agent -s)"

# 添加密钥到 Agent
ssh-add ~/.ssh/id_rsa_github
ssh-add ~/.ssh/id_rsa_gitee

3. 创建 SSH 配置文件

~/.ssh/config 中配置规则:

touch ~/.ssh/config

编辑内容:

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

# Gitee
Host gitee.com
    HostName gitee.com
    User git
    IdentityFile ~/.ssh/id_rsa_gitee

4. 添加公钥到平台

GitHub

  1. 复制公钥内容:

    cat ~/.ssh/id_rsa_github.pub
    
  2. 粘贴到 GitHub SSH Keys 页面。

Gitee

  1. 复制公钥内容:

    cat ~/.ssh/id_rsa_github.pub
    
  2. 粘贴到 GitHub SSH Keys 页面。

5. 测试 SSH 连接

# 测试 GitHub
ssh -T git@github.com
# 成功提示:Hi <username>! You've successfully authenticated...

# 测试 Gitee
ssh -T git@gitee.com
# 成功提示:Hi <username>! You've successfully authenticated...

6. 关联本地仓库与远程仓库

# 关联 GitHub(自定义远程仓库名)
git remote add github git@github.com:username/repo.git

# 关联 Gitee(自定义远程仓库名)
git remote add gitee git@gitee.com:username/repo.git

# 查看远程仓库
git remote -v

7. 推送代码

# 推送到 GitHub
git push github master

# 推送到 Gitee
git push gitee master

注意事项

  1. Git 提交邮箱配置
    SSH 密钥的邮箱仅用于标识密钥,Git 提交邮箱需单独配置:

    # 全局邮箱(所有仓库默认)
    git config --global user.email "your-email@example.com"
    
    # 项目级邮箱(覆盖全局)
    git config user.email "project-email@example.com"
    
  2. 密钥文件权限

    • 确保 ~/.ssh 目录权限为 700
    chmod 700 ~/.ssh
    
    • 密钥文件权限为 600
    chmod 600 ~/.ssh/id_rsa_*
    
  3. HTTPS 与 SSH 区别

    • 推荐使用 SSH 协议,避免 HTTPS 每次输入密码。
    • 若使用 HTTPS,需配置 Git 凭据存储:
    git config --global credential.helper store
    
posted @ 2025-05-06 23:57  RK5123153  阅读(118)  评论(0)    收藏  举报