生成第一个账号的密钥:


先确保你已经有多个git账号(如:一个github的账号、一个码云的账号、...)。

在Git Bash Here的控制台里输入:


git config --global user.name "你的名称"   回车

git config --global user.email "你的邮箱"    回车


这里的邮箱是你申请git账号时的邮箱,不报错就是正确的,继续往下走

输入 ssh-keygen -t rsa -C "你的邮箱"  回车,再连续3次回车见下图:


此时看下图中有一行提示:Your public key has been saved in /c/Users/xxx/.ssh/id_rsa.pub

到该路径(C/Users/xxx/.ssh)可以看见两个文件:id_rsa、id_rsa.pub 。

多个git账号的登录与切换_git

复制密钥保存到git账号里。

---------------------------------

第二个git账号的配置:

1、新建user2的SSH Key

#新建SSH key:
$ cd ~/.ssh # 切换到C:\Users\Administrator\.ssh
ssh-keygen -t rsa -C "mywork@email.com" # 新建工作的SSH key
# 设置名称为id_rsa_work
Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa): id_rsa_work

2、新密钥添加到SSH agent中

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

ssh-add ~/.ssh/id_rsa_work

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

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

3、修改config文件
在~/.ssh目录下找到config文件,如果没有就创建:

touch config        # 创建config

然后修改如下:
我的config配置如下:

# 该文件用于配置私钥对应的服务器
# Default github user(first@mail.com)
Host github.com
HostName github.com
User git
IdentityFile C:/Users/Administrator/.ssh/id_rsa

# second user(second@mail.com)
# 建一个github别名,新建的帐号使用这个别名做克隆和更新
Host github2
HostName github.com
User git
IdentityFile C:/Users/Administrator/.ssh/id_rsa_work

如果存在的话,其实就是往这个config中添加一个Host:

#建一个github别名,新建的帐号使用这个别名做克隆和更新
Host github2
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa2

其规则就是:从上至下读取config的内容,在每个Host下寻找对应的私钥。这里将GitHub ​​SSH仓库地址中的git@github.com替换成新建的Host别名如​​:github2,那么原地址是:​​git@github.com​​:funpeng/Mywork.git,替换后应该是:github2:funpeng/Mywork.git.

4、打开新生成的~/.ssh/id_rsa2.pub文件,将里面的内容添加到GitHub后台。

可不要忘了添加到你的另一个github帐号下的SSH Key中。

VI编辑器:

:wq:在命令模式下,执行存盘退出操作;


多个git账号的登录与切换_User_02

clone尽量用ssh

git clone ssh