Skip to content

Git单工作站多账户配置

545字约2分钟

Git

2024-07-09

很多时候程序员都会有多个Git账户, 也许你想要把工作和个人开发账户分开, 这个时候就涉及到在同一个工作站(主机)上对多个Git账户进行操作. 我参考了很多做法, 找到了目前的一个解决方案. 不是太完美, 因为实测过程中发现需要在每个项目第一次使用时配置一次用户名和邮箱.

首先, 我们先假设我们需要配置的两个Git账户如下:

账号usernameemail网站
1alicealice@gmail.comGitlab
2bobbob@163.comGitHub

1. 生成公私钥

使用管理员身份运行Git Bash:

## 1) 生成alice在Gitlab上的公私钥文件
ssh-keygen -t rsa -f ~/.ssh/id_rsa_gitlab -C "alice@gmail.com" 

## 2)生成bob在GitHub上的公私钥文件
ssh-keygen -t rsa -f ~/.ssh/id_rsa_github -C "bob@163.com"

执行完这两个命令后可以在C:\\用户\\<username>\\.ssh路径下找到4个文件, 分别是两个账户的公钥和私钥.

序号文件名含义
1id_rsa_gitlabalice的私钥
2id_rsa_gitlab.pubalice的公钥
3id_rsa_githubbob的私钥
4id_rsa_github.pubbob的公钥

2. 配置公钥

分别登录进入Gitlab和GitHub进行公钥的配置. 在设置中找到SSH Key的相关设置, 点击New SSH key, 将公钥文件中的内容复制添加到里面.

3. 激活公钥

在Git Bash中执行:

Gitlab

## 1) 激活公钥
ssh -T git@gitlab.com -i ~/.ssh/id_rsa_gitlab

## 2)授权
yes

GitHub

## 1) 激活公钥
ssh -T git@github.com -i ~/.ssh/id_rsa_github

## 2) 授权
yes

4. 添加私钥文件

## 1) 打开服务
eval `ssh-agent`
## 2) 添加Gitlab
ssh-add ~/.ssh/id_rsa_gitee
## 3) 添加GitHub
ssh-add ~/.ssh/id_rsa_github

5. 配置config文件

config文件, 一般保存在~/.ssh/目录里, 用于切换多个gitee、github账号. 将config文件中关于username和email的global配置删除, 然后改为以下内容:

Host gitlab.com
HostName gitlab.com
IdentityFile C:\\用户\\<username>\\.ssh\\id_rsa_gitlab
PreferredAuthentications publickey
User alice


Host github.com
HostName github.com
IdentityFile C:\\用户\\<username>\\.ssh\\id_rsa_github
PreferredAuthentications publickey
User bob