likes
comments
collection
share

同一客户端下使用多个 Git 账号

作者站长头像
站长
· 阅读数 7

我们在日常使用 Git 进行文件管理时,避免不了会使用多个账号的情况(也就是在同一台电脑上使用多个 Git 账号)。自己在家开发一些小项目就托管在 Github 上面,而在公司的话会用到另外一个账号,可能是 GitLab 账号进行管理,或者是自己想要搭建一个个人博客并托管在另一个账号,那么单纯的 HTTPS 就不足以支持两个账号在同一客户端进行使用了,这时就需要用到 SSH 来进行管理。

PS: 这篇博客主要是想要记录自己多个 Git 账号的配置过程,以备查阅。参考了几篇博客,对内容进行了一下整合,参考链接附在文末。


1. 清除 Git 的全局设置

git config --global --unset user.name
git config --global --unset user.email

2. 生成新的 SSH keys

用 ssh-keygen 命令生成一组新的 id_rsa_new 和 id_rsa_new.pub

ssh-keygen -t rsa -C "new email"

在生成第一组 id_rsaid_rsa.pub_ 可以选用默认的文件名,在出现提示输入文件名的时候要输入一个不同的文件名,**比如:**这里填的是 id_rsa_new

Enter file in which to save the key (~/.ssh/id_rsa): id_rsa_new

**注:**Windows 用户和 Mac 用户的区别就是,mac 中 .ssh 文件夹在根目录下,所以表示成 ~/.ssh/,而 Windows 用户是 C:\Users\Administrator\.ssh

执行 ssh-agent 让 ssh 识别新的私钥

因为默认只读取 id_rsa,为了让 SSH 识别新的私钥,需将其添加到 SSH agent 中:

ssh-add ~/.ssh/id_rsa_new

如果出现 Could not open a connection to your authentication agent 的错误,就试着用以下命令:

ssh-agent bash
ssh-add ~/.ssh/id_rsa_new

3. 配置 ~/.ssh/config 文件

# 该文件用于配置私钥对应的服务器
Host git@github.com    # 别名,随便定 后面配置地址有用
    HostName https://github.com
    User git
    IdentityFile ~/.ssh/id_rsa    # 密钥文件的地址,注意是私钥

# second user(second@mail.com)
Host git@code.xxxxxxx.com
    HostName https://code.xxxxxxx.com
    User git
    IdentityFile ~/.ssh/id_rsa_new

PS: HostName 如果添加 https:// 前缀可能发生 public key 不能识别的情况,所以可以直接改为 github.com

4. 添加新的 SSH keys 到新账号的 SSH 设置中

5. 测试一下

$ ssh -T git@github.com    # 此处是 Host 后面定义的别名
Hi xxx! You’ve successfully authenticated, but GitHub does not provide shell access.

# 上面是 github 的成功返回语句,下面是 gitlab 的成功返回语句。

$ ssh -T git@xxxxxx.com
Welcome to GitLab, xxx!  

链接:www.jianshu.com/p/89cb26e5c… 来源:简书

参考资料

blog.csdn.net/onTheRoadTo…

gist.github.com/suziewong/4…

转载自:https://juejin.cn/post/6844903902916132878
评论
请登录