一直以来,我就使用一个 GitHub账号,不知什么原因,不能添加协作者也不能 Fork 其他项目了。于是又注册了一个新的,现在我就有了两个 GitHub 账号,那么使用 ssh clone 就得额外配置。因为需要在几台电脑上配置,本文就简单记录一下配置的教程,也方便以后查询方便。
假如我们两个github的账户名是 chengxulvtu1 和 chengxulvtu2
创建 ssh key
打开终端,切换到.ssh 目录
cd ~/.ssh
输入下面的命令分别为两个GitHub账号生成 ssh key
ssh-keygen -t rsa -C "chengxulvtu1@gmail.com" -f id_rsa_chengxulvtu1
ssh-keygen -t rsa -C "chengxulvtu2@gmail.com" -f id_rsa_chengxulvtu2
执行完上面的命令,会生成4个文件 id_rsa_chengxulvtu1,id_rsa_chengxulvtu1.pub, id_rsa_chengxulvtu2,id_rsa_chengxulvtu2.pub
添加 ssh key
分别登录两个GitHub 账号,在 “Settings —> Access—> SSH and GPG keys” 中 或直接打开网址 Add new SSH key (github.com) 添加 ssh key。
将 id_rsa_chengxulvtu1.pub 的内容添加到第一个 GitHub 账号
将id_rsa_chengxulvtu2.pub 的内容添加到第二个 GitHub 账号
添加后使用下面的命令测试是否 ssh key 添加是否成功
ssh -T git@github.com -i ~/.ssh/id_rsa_chengxulvtu1
ssh -T git@github.com -i ~/.ssh/id_rsa_chengxulvtu2
会返回
Hi chengxulvtu1! You've successfully authenticated, but GitHub does not provide shell access.
和
Hi chengxulvtu2! You've successfully authenticated, but GitHub does not provide shell access.
说明配置没问题。
配置不同账号使用不同的ssh key
在 ~/.ssh 目录中,打开或创建 config 文件,添加以下内容
# 配置 chengxulvtu1
Host chengxulvtu1.github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_chengxulvtu1
# 配置 chengxulvtu2
Host chengxulvtu2.github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_chengxulvtu2
用法
假如 chengxulvtu1 账号中有一个项目 cxlt.test
原来
git clone git@github.com:chengxulvtu/cxlt.test.git
现在
git clone git@chengxulvtu1.github.com:chengxulvtu/cxlt.test.git
取消全局用户名和邮箱配置,为每个仓库单独设置
git config --global --unset user.name
git config --global --unset user.email
git config user.name "用户名"
git config user.email "邮箱"