配置gitee和github密钥并实现自动登录

发表时间:2026-01-28 分类:技术 标签:git

有时候因为工作需要,同时使用多个Git仓库,为实现免登录访问,需要配置不同的密钥。以下介绍Git中同时配置Gitee和GitHub的SSH密钥,并设置不同目录使用不同平台,目标是实现在~/gitee下就使用Gitee的密钥、在~/.github下使用Github的密钥。

生成两对密钥

创建Github的密钥(RSA算法):

ssh-keygen -t rsa -b 4096 -C "your-email@example.com" -f ~/.ssh/id_rsa_github

如果要使用ed25519算法,则使用以下参数:

ssh-keygen -t ed25519 -C "your-email@example.com" -f ~/.ssh/id_ed25519_github

接下去创建 Gitee的密钥:

ssh-keygen -t rsa -b 4096 -C "your-email@example.com" -f ~/.ssh/id_rsa_gitee

配置config文件

创建或编辑 ~/.ssh/config 文件:

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

# Gitee配置
Host gitee.com
    HostName gitee.com
    User git
    IdentityFile ~/.ssh/id_ed25519_gitee   # 或 id_rsa_gitee
    IdentitiesOnly yes

将公钥添加到平台

首先复制公钥:

# 查看GitHub公钥
cat ~/.ssh/id_ed25519_github.pub

# 查看Gitee公钥
cat ~/.ssh/id_ed25519_gitee.pub

添加到GitHub

  1. 登录GitHub → Settings → SSH and GPG keys
  2. 点击 “New SSH key”
  3. 粘贴 ~/.ssh/id_ed25519_github.pub 的内容

添加到Gitee:

  1. 登录Gitee → 设置 → SSH公钥
  2. 粘贴 ~/.ssh/id_ed25519_gitee.pub 的内容

测试连接

测试GitHub连接

ssh -T git@github.com
# 成功会显示: Hi username! You've successfully authenticated...

测试Gitee连接
```bash
ssh -T git@gitee.com
# 成功会显示: Hi username! You've successfully authenticated...