git 同一台机器上管理多个github账户

发布时间 2023-09-22 22:34:29作者: 豁然高

同一台机器上一个ssh key只能管理一个github账户,
如果给第二个github账户添加同一个ssh key时会提示以下错误

Key is already in use

 

所以要想在同一台机器上管理多个github账户,那就需要使用多个ssh key

1.创建一个新的ssh key

ssh-keygen -t rsa -C "youreothermail@example.com" -f ~/.ssh/id_rsa_work

如果没有 -f 选项,那么默认生成的文件为id_rsa和id_rsa.pub
使用 -f 选项可以指定生长的ssh key 的文件名,上面的例子就会生成 id_rsa_work和id_rsa_work.pub

 

创建一个新的ssh key后,..ssh/文件夹中就有以下两对ssh key

id_rsa
id_rsa.pub
id_rsa_work
id_rsa_work.pub

 

2.配置 SSH 配置文件

~/.ssh/ 目录下创建或编辑 config 文件,配置每个 GitHub 账户对应的 SSH 密钥。示例配置如下:

# GitHub account 1
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa

# GitHub account 2
Host github.work
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_work

github.com和github.work是github.com的别名

 

3. 分别将id_rsa.pub和id_rsa_work.pub添加到不同的github账户中,比如以下两个账户

git@github.com:accout1
git@github.com:accout2

4. 从远程库clone到本地或者将本地库关联到远程库

从远程库clone到本地

git clone github.com:account1/repo1.git
git clone github.work:account2/repo2.git

将本地库关联到远程库

git remote add origin git@github.com:account1/repo1.git
git remote add origin git@github.work:account2/repo2.git

使用别名时就会在.ssh/config文件中找到别名对应的IdentityFile(秘密键文件),从而与对应的github账户中添加的公开键进行认证