Git命令行处理多个Github账户

问题引入

由于个人原因创建了另一个Github账号来托管项目,当创建好仓库之后将项目上传到Github仓库时,服务器返回以下错误:

1
2
3
4
ERROR: Permission to user02/TestGithub.git denied to user01.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

经过检查发现是因为我使用了SSH来克隆仓库,所以Git会默认寻找~/.ssh目录下名字为id_rsa的key,而不是我为此Github账户单独配置的名为id_rsa_jun28的key。

当前~/.ssh目录结构内容如下:

id_rsa
id_rsa.pub
id_rsa_jun28
id_rsa_jun28.pub
known_hosts

解决方法

~/.ssh目录下配置config文件,如果没有则新建一个,添加如下内容:

1
2
3
4
5
6
7
8
9
10
11
#第一个Github账户
Host host01
HostName github.com
User user01
IdentityFile ~/.ssh/id_rsa

#第二个Github账户
Host host02
HostName github.com
User user02
IdentityFile ~/.ssh/id_rsa_jun28

其中Host的内容为自定义名称,在后续操作中会用到此内容,User内容为自己的Github用户名,IdentityFile为相应Github账户使用的SSH key的文件路径。

当配置好config文件后,相应的在命令行需要更改仓库地址URL。

1
git@github.com:user02/TestGithub.git

更改为

1
git@host02:user02/TestGithub.git

这样Git就会去匹配config文件里Host名称为host02的所对应的SSH key。
最后附上Git命令行完整流程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
➜  TestGithub git init
Initialized empty Git repository in /Users/Ivan/Dev/workspace/TestGithub/.git/
➜ TestGithub git:(master) echo "# TestGitHub" >> README.md
➜ TestGithub git:(master) ✗ git add ./
➜ TestGithub git:(master) ✗ git commit -m "First commit"
[master (root-commit) cafede2] First commit
1 file changed, 1 insertion(+)
create mode 100644 README.md
➜ TestGithub git:(master) git remote add origin git@host02:user02/TestGithub.git
➜ TestGithub git:(master) git push -u origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 232 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To git@host02:user02/TestGithub.git
* [new branch] master -> master
Branch master set up to track remote branch master from origin.

大功告成!!

说明,此方法仅对采用了SSH克隆仓库的方式有效,针对Https方式本人还没有亲自测验过,如果大家有建议或者方法,欢迎指正。

0%