如何在一台机器上管理多个 Github 账号 (New)
我们有时候需要在一台电脑上管理两个或者两个以上的 GitHub 账号,例如要在电脑上同时使用个人和公司的Github账号,那么如何操作呢?
(以下方法也适合管理 GitHub 和 Gitlab 账号。)
步骤
创建新的 SSH Key
假设个人电脑上已经有了一个正使用的 GitHub 账号 user_a ,现在添加第二个 GitHub 账号user_b的配置。
打开终端生成一个新的 SSH Key:
$ ssh-keygen -t rsa -C "user_b@gmail.com"
注意,新生成的密钥不要覆盖原来的,在 ssh-keygent
运行中让新生成的 key 命名为 user_b
。
在我电脑里面,它被保存在 ~/.ssh/user_b_id_rsa
把新生成的 SSH key 添加到 ssh-agent:
$ eval "$(ssh-agent -s)"
$ ssh-add ~/.ssh/user_b_id_rsa
参考:Generating a new SSH key and adding it to the ssh-agent
在第二个 GitHub 账户里面添加 新生成 user_b_id_rsa.pub
登录第二个Github 账号,把 user_b_id_rsa.pub
添加到账号里面。
参考: Adding a new SSH key to your GitHub account
创建配置文件
假设 user_a 与 user_b 的 SSH key 相关文件命名如下:
Github 帳戶 | Id_rea | Id_rsa.pub |
---|---|---|
user_a | user_a_id_rsa | user_a_id_rsa.pub |
user_b | user_b_id_rsa | user_a_id_rsa.pub |
在 ~/.ssh 目录下新建 config 文件。
$ touch ~/.ssh/config
编辑 config 文件:
Host user_a-github.com
HostName github.com
User git
IdentityFile ~/.ssh/user_a_id_rsa
Host user_b-github.com
HostName github.com
User git
IdentityFile ~/.ssh/user_b_id_rsa
测试连接
$ ssh -T git@user_a-github.com
$ ssh -T git@user_b-github.com
若成功,都会接收到类似这样的信息:
Hi user_a! You've successfully authenticated, but GitHub does not provide shell access.
Hi user_b! You've successfully authenticated, but GitHub does not provide shell access.
测试用把仓库提交到第二个 Github 账号
新建一个文件夹,初始化为仓库,创建第一个 commit
$ mkdir Test
$ cd Test
$ git init
$ git commit -am "first commit"
$ git remote add origin git@user_b-github.com:user_b/testing.git
$ git branch -M main
$ git push -u origin main
注意:为本地仓库添加远程地址时,要替换为 config 文件里面的 Host 。
例如此处: user_b-github.com
git remote add origin git@user_b-github.com:user_b/testing.git
参考
- How to Work with GitHub and Multiple Accounts
- Using multiple github accounts with ssh keys
- Generating a new SSH key and adding it to the ssh-agent
- Adding a new SSH key to your GitHub account
本作品采用《CC 协议》,转载必须注明作者和本文链接