同一台机器,如何配置多个github账户信息

git上是现在十分常用的版本控制工具,GitHub作为其代码的托管中心, 下面按照设置两个账户来开始详细的介绍:

第一步:生成需要的key

$ ssh-keygen -t rsa -C "[email protected]" -f ~/.ssh/id_rsa_one
该公钥和私钥包含了你邮箱的信息,具有随机不可复现性

BEGIN-NOTICE:
ssh-keygen -t rsa -C “any comment can be here” -f path
-t rsa The type of the key to generate密钥的类型
-C "youremail" comment to identify the key用于识别这个密钥的注释
所以这个注释你可以输入任何内容,很多网站和软件用这个注释作为密钥的名字
-f path新生成的密钥的地址路径
END-NOTICE

假设我们生成了如下两个key

.ssh/id_rsa_one
.ssh/id_rsa_one.pub
.ssh/id_rsa_two
.ssh/id_rsa_two.pub


第二步:设置SSH

本地需要识别刚才生产的SSH-KEY,就需要使用一下命令进行添加

1
2
3
# 使用-K可以将私钥添加到钥匙串,不用每次开机后还要再次输入这条命令
$ ssh-add -K ~/.ssh/id_rsa_one
$ ssh-add -K ~/.ssh/id_rsa_two

通过下面命令,查看key的设置:

1
$ ssh-add -l

建立对应的config

1
2
3
4
5
6
7
8
9
Host one.github.com # 设置的用于链接的名字,可以随便设置
HostName github.com # github的主机地址(相当于我们的IP,只不过做了域名对应)
User git # 默认的User就是git
IdentityFile ~/.ssh/id_rsa_one # 我们添加的私钥的地址(公钥在github上对应)
Host two.github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_two


第三步:添加公钥到我们不同的远程主机(这里就是我们不同的github账号)

由于github直接提供复制,我们直接对pub公钥进行复制,然后粘贴到每个账户对应的设置中去。
将公钥复制到github上之后,我们就可以开始测试他们的连接了

1
2
3
4
5
6
$ ssh -T one.github.com
$ ssh -T two.github.com
# 执行后如果出现信息,就表示验证通过了:
Hi yourname! You've successfully authenticated, but GitHub does not provide shell access.
# 这个地方的 Yourname 指的是你的对应的github账户的名字,如果出现的不是对应的账户的名字,
也说明是没有成功。


第四步:设置git区分与注意事项

  1. 首先要做的是我们克隆仓库和新建仓库后推送到远程的时候的设置
    1
    2
    3
    # 本地新建,然后推送
    $ git remote add origin [email protected]/github_name/respo_name.git
    $ git remote add origin [email protected]/github_name/respo_name.git

这样才能保证连接的是对应的仓库

  1. 如果是clone的仓库,最好也这么修改,便于区分

    1
    2
    3
    # 远程新建,本地克隆
    $ git clone [email protected]/github_name/respo_name.git
    $ git clone [email protected]/github_name/respo_name.git
  2. 矫正respo下面的.git/config里的内容

  • git 命令修改其内容

    1
    2
    3
    $ git config --local user.name "yourname"
    $ git config --local user.email "youemail"
    # 注意的是,这个邮箱必须是你这个仓库对应的github的注册邮箱,名字无所谓,但是建议也一致
  • 直接进文件修改器内容

    1
    2
    3
    [remote "origin"]
    url = https://github.com/github_name/respo_name.git
    fetch = +refs/heads/*:refs/remotes/origin/*

如果返现这里的内容不一致,请修改过来也