一个电脑两个git账户

因为之前在实习,有一个公司的git账号,最近想把自己之前的注册的git账号拿起来维护,结果在push的时候遇到permission denied。上网查了下解决了,自己记录一下。

###1.解决ssh密钥
需要为两个账户,比如one和two各准备一个密钥
可以先删除之前的默认名的密钥,生成新的

rm ~/.ssh/id_rsa.pub
rm ~/.ssh/id_rsa

分别生成新的 id_rsa 私钥 , id_rsa.pub 公钥

ssh-keygen -t rsa -C "your-email-address" -f "rsa_name"

比如id_rsa_one和id_rsa_two
分别登录one和two的账号,在 Account Settings 的 SSH Keys 里,点 Add SSH Keys ,将公钥(.pub文件)中的内容粘贴到”Key”中,并输入”Title”.

###2.设置ssh config文件
新建文件
cd ~/.ssh/
touch config
打开.ssh文件夹下的config文件,进行配置

# default
Host one.github.com//可以为github.com默认
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_one

# two
Host two.github.com  # 前缀名可以任意设置
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_two

简单分析下原因,我们可以发现 ssh 客户端是通过类似:
git@github.com:one/one.github.com.git
这样的 git 地址中的 User 和 Host 来识别使用哪个本地私钥的。
很明显,如果 User 和 Host 始终为 git 和 github.com,那么就只能使用一个私钥。
所以需要上面的方式配置,每个账号使用了自己的 Host,每个 Host 的域名做 CNAME 解析到 github.com,这样 ssh 在连接时就可以区别不同的账号了。

测试

ssh -T git@one.github.com    # 测试one ssh连接
#Hi ***! You've successfully authenticated, but GitHub does not provide shell access.
ssh -T git@two.github.com    # 测试two ssh连接
#Hi ***! You've successfully authenticated, but GitHub does not provide shell access.

###3.新建本地项目
使用git init 或git clone
查看git项目的配置

git config --list

查看one的remote.origin.url=git@github.com:one/one.github.com.git 注:后半部分是仓库名
查看two的remote.origin.url=git@github.com:two/two.github.com.git
由于one使用的是默认的Host,所以不需要修改,但是two使用的是two.github.com,则需要进行修改

git remote rm origin
git remote add origin git@two.github.com:two/two.github.com.git

###4.设置完成后就可以上传代码了

git add -A
git commit -m "your comments"
git push

一个客户端设置多个github账号