Git多账号配置

起因

若要在同一台电脑上使用两个及以上的GitHub账号,第一个账号已存在电脑中,若要提交到另一个账号就会提示

1
remote: Permission to 用户名/xxx.git denied to 另一个用户名.

临时解决方法

若不想同时支持两个账号,只想删除之前存储的账号。若系统是Win10(其他系统类似,找到凭据管理器即可),可在设置中搜索凭据 ,打开凭据管理器 ,找到Windows 凭据 ,在普通凭据中找到GitHub账号,将其删除即可。这样在提交时会弹出让你输入账号密码的提示框,输入新账号即可。

终极解决方案

创建SSH公钥私钥

1
ssh-keygen -t rsa -C "your_email@youremail.com"

输出显示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ ssh-keygen -t rsa -C "your_email@youremail.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/用户名/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/用户名/.ssh/id_rsa.
Your public key has been saved in /c/Users/用户名/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:aTdcC........................mQAU your_email@youremail.com
The key's randomart image is:
+---[RSA 2048]----+
| .Eo. +o=.....o |
| . o *o+o..+oo|
| . . B +. *.=.o|
| . = =o + * +.|
| + +S.= + ...|
| * ..oo + .|
| . .o |
| Eo . . . |
| o . .. |
+----[SHA256]-----+

上面第一步是会让你修改默认的存储路径,直接回车即可;

第二步是输入密码,也可直接回车不设置密码;

第三步是确认密码,若没设置密码,也直接回车。

之后就成功生成了密钥,打开.ssh文件夹,用文本编辑器打开id_rsa.pub 文件,复制内容到剪贴板

配置公钥到GitHub

打开https://github.com/settings/keys ,点击 New SSH Key按钮,输入标题后,粘贴到下面的Key一栏,保存即可。

重复上述操作生成另一个key,可先将生成的rsa文件重命名,然后保存到相应的账号下即可。

配置config文件

.ssh目录下创建config文本文件并完成相关配置,此步骤最为关键。

每个账号单独配置一个Host,每个Host要取一个别名,每个Host主要配置HostNameIdentityFile两个属性即可。

Host的名字可以取为自己喜欢的名字,不过这个会影响git相关命令,例如:

Host mygithub 这样定义的话,命令如下,即git@后面紧跟的名字改为mygithub

git clone git@mygithub:用户名/项目名

内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 该文件用于配置私钥对应的服务器
# Default github user(first@mail.com)
Host github1
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

执行测试

1
ssh -T git@Host别名

上述命令会自动生成known_hosts文件把私钥配置进文件中

内容如下:

1
2
3
4
5
6
$ ssh -T git@percy
The authenticity of host 'github.com (13.250.177.223)' can't be established.
RSA key fingerprint is SHA256:nThbg.............................Kw6E5SY8.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,13.250.177.223' (RSA) to the list of known hosts.
Hi percy! You've successfully authenticated, but GitHub does not provide shell access.

看到上述提示就说明链接成功

更改URL

也可以说这是多账号的缺点吧,就必须要使用SSH协议,而不能再使用HTTPS了,将项目下.git/config中的url改为git@Host别名:GitHub用户名/项目名.git