Windows下Gitlab多账号(3个及以上)SSH配置

多 Git 账号管理(SSH 模式)

动机

我在使用多个 Git 账号时经常遇到麻烦:每次切换账号都要重新登录,尤其是浏览器身份验证时。我默认浏览器使用 Edge,但 GitHub 的登录信息保存在 Chrome 中,跳转验证让人头皮发麻。
公司使用 GitLab,强制要求 SSH,而我个人的 GitHub 账号之前是用 HTTPS。频繁在公司和个人项目间切换,要反复输入密码,还经常需要改 git config 设置用户名和邮箱。
为了解决这些问题,我统一改用 SSH,并配置多个密钥和 .gitconfig,实现账号之间的无缝切换。

适用于以下场景

  1. 公司项目强制要求使用 SSH 方式进行 clone 或其他 Git 操作。
  2. 多账号频繁使用时,推荐使用 SSH;偶尔使用可选择 GitHub Desktop、封装 Git 的 IDE,或浏览器登录切换。
  3. 拥有 3 个及以上 Git 账号时,浏览器切换效率低,建议使用 SSH。

1. 生成 SSH 密钥对

为每个账号生成一对公钥和私钥:

# 个人 GitHub 账号 ssh-keygen -t ed25519 -C "xxxyyy@gmail.com" -f ~/.ssh/id_ed25519_personal  # 公司 GitHub 账号 ssh-keygen -t ed25519 -C "xxxyyy@your-company.com" -f ~/.ssh/id_ed25519_company_github  # 公司 GitLab 账号 ssh-keygen -t ed25519 -C "xxxyyy@your-company.com" -f ~/.ssh/id_ed25519_company_gitlab 

Windows下Gitlab多账号(3个及以上)SSH配置


2. 配置 SSH 配置文件

C:Users你的用户名.sshconfig 中配置如下内容:

# Company GitHub account Host github.com-company     HostName github.com     User git     IdentityFile ~/.ssh/id_ed25519_companyGithub  # Company GitLab account Host gitlab.com-company     HostName gitlab.com     User git     IdentityFile ~/.ssh/id_ed25519_companyGitlab 	 # Personal GitHub account Host github.com-personal     HostName github.com     User git     IdentityFile ~/.ssh/id_ed25519_personal 

3. 创建账号专属的项目目录和配置文件

3.1 创建三个文件夹

建议将不同账号的项目放在不同路径中,例如:

C:/Projekte/Personal/ C:/Projekte/CompanyGithub/ C:/Projekte/CompanyGitlab/ 

Windows下Gitlab多账号(3个及以上)SSH配置

3.2 分别创建 .gitconfig 文件

个人 GitHub 账号:C:Users你的用户名.gitconfig-personal

[user] 	name = xxxyyy 	email = xxxyyy@gmail.com 

公司 GitHub 账号:C:Users你的用户名.gitconfig-company-github

[user] 	name = xxxyyy-dev0511 	email = xxxyyy@your-company.com 

公司 GitLab 账号:C:Users你的用户名.gitconfig-company-gitlab

[user] 	name = xxxyyy 	email = xxxyyy@your-company.com 

3.3 验证配置

git config --file C:/Users/你的用户名/.gitconfig-personal --list git config --file C:/Users/你的用户名/.gitconfig-company-github --list git config --file C:/Users/你的用户名/.gitconfig-company-gitlab --list 

4. 配置全局 .gitconfig 文件

C:Users你的用户名.gitconfig 中添加如下内容:

[user] 	name = xxxyyy 	email = xxxyyy@your-company.com  [includeIf "gitdir:C:/Projekte/Personal/"]     path = C:/Users/JinyaoChen/.gitconfig-personal  [includeIf "gitdir:C:/Projekte/CompanyGithub/"]     path = C:/Users/JinyaoChen/.gitconfig-company-github  [includeIf "gitdir:C:/Projekte/CompanyGitlab/"]     path = C:/Users/JinyaoChen/.gitconfig-company-gitlab 

5. 使用 SSH clone 多账号项目

5.1 Clone 公司 GitLab 项目

git clone git@gitlab.com-company:ComnanyRepo/kelvin5/iris/k5-graphql.git 

5.2 Clone 公司 GitHub 项目

git clone git@github.com-company:ComnanyRepo/Grafana-Docker.git 

5.3 Clone 个人 GitHub 项目

git clone git@github.com-personal:cjy513203427/IADBE.git 

发表评论

评论已关闭。

相关文章