Git 单工作站多账户配置
很多时候程序员都会有多个 Git 账户,也许你想要把工作和个人开发账户分开,这个时候就涉及到在同一个工作站(主机)上对多个 Git 账户进行操作。我参考了很多做法,找到了目前的一个解决方案。不是太完美,因为实测过程中发现 需要在每个项目第一次使用时配置一次用户名和邮箱。
首先,我们先假设我们需要配置的两个 Git 账户如下:
账号 | username | 网站 | |
---|---|---|---|
1 | alice | alice@gmail.com | Gitlab |
2 | bob | bob@163.com | GitHub |
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 个文件,分别是两个账户的公钥和私钥。
序号 | 文件名 | 含义 |
---|---|---|
1 | id_rsa_gitlab | alice 的私钥 |
2 | id_rsa_gitlab.pub | alice 的公钥 |
3 | id_rsa_github | bob 的私钥 |
4 | id_rsa_github.pub | bob 的公钥 |
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
贡献者
更新日志
2025/3/6 02:33
查看所有更新日志
876bb
-improve(docs): use chinese punctuation于1289a
-improve(docs): delete extra whitespace and blank lines于c2111
-modify(docs): remanage folders and rename files于c085a
-docs: update docs于bcf18
-docs: update docs于96e66
-docs: update docs于0440f
-更改navbar于71726
-升级主题+整理文章格式于978a9
-整理文章格式于547bb
-升级主题+新增文章+修改格式于