Git 设置多个账号

 

清除原有全局设置

  • 这步不是必须的,如果你没有使用

 

 git config --global user.name 'xxxxx' 
 git config --global user.email 'xxxx' 

设置过全局用户名、email 等信息,则不用清除原有设置。(当然如果你也记不得了,那就这么操作下吧)

  • 使用 git 命令取消全局设置

 

取消global
git config --global --unset user.name
git config --global --unset user.email



作者:ifjgm
链接:https://www.jianshu.com/p/cacf91579268
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

生成ssh 密钥

  • 首先我们在~.ssh/ 文件夹下创建companygithub 文件夹,命令如下

 

mkdir company
mkdir github
  • 生成Gitlab 对应账号的ssh密钥,命令如下

 

ssh-keygen -t rsa -C "[email protected]"
  • 执行完上面的命令后,命令行会弹出如下提示

 

Enter file in which to save the key (/Users/tuoanlan/.ssh/id_rsa):
  • 输入地址保存rsa 文件到指定路径,如下(注意,我当前在.ssh 文件夹下,所以主意你指定的路径是否正确)

 

 company/id_rsa_company
  • 然后会让你输入密码的提示

 

Enter passphrase (empty for no passphrase):
  • 这里一般不用输入密码,我们直接回车两次(不输入 passphrase
  • 当弹出如下提示

 

Your identification has been saved in company/id_rsrsa_company.
Your public key has been saved in company/id_rsrsa_company.pub.

说明ssh 密钥已经生成并保存在 company 文件夹下 id_rsa_companyid_rsa_company.pub

二:将公钥添加到网站

  • 复制公钥,命令如下(当然你也可以手动复制)

 

pbcopy <id_rsa_company.pub
  • 粘贴 到ssh key 的框中,然后点击 Add key 即可。如下图所示

    image

  • 这里仅仅以 Gitlab 为例子,其他网站类似,不多赘述。

配置

  • .ssh 文件夹下创建 config 文件,并添加如下内容

 

# The git info for company
Host qdjr.git.zhudb.com                 # 写公司git 地址
HostName qdjr.git.zhudb.com             # 写公司git 地址
User git                                # 可以写邮箱名称,也可以写 git 账号
IdentityFile ~/.ssh/company/id_rsa      #对应公司 git 账号密钥路径,注意不要写错

# The git info for github           
Host github.com                             # 写 github 的地址
HostName github.com                         # 写 github 的地址
User git                                    # 可以写邮箱名称,也可以写 git 账号
IdentityFile ~/.ssh/github/id_rsa_github    # 对应github 密钥路径,注意不要写错


以上内容只是示例,如果想直接复制后修改,请复制如下内容到 config

 

# The git info for company
Host  qdjr.git.zhudb.com
HostName  qdjr.git.zhudb.com
User [email protected]
IdentityFile ~/.ssh/company/id_rsa_company

# The git info for github
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/github/id_rsa

把专用密钥添加到 ssh-agent 的高速缓存中

执行命令 ssh-addIdentityFile 添加到 ssh-agent高速缓存中,执行如下命令

 

 ssh-add ~/.ssh/company/id_rsa_company 
 ssh-add ~/.ssh/github/id_rsa

验证是否配置成功

  • 执行如下命令,验证是否配置成功

 

 ssh -T [email protected]
  • 第一次执行可能会弹出如下提示

 

The authenticity of host 'qdjr.git.zhudb.com (121.43.184.183)' can't be established.
ECDSA key fingerprint is SHA256:BGEoBwmuXjA3mzMGnU2dxvpdlPv8pxBDZgA3SKOFMVs.
Are you sure you want to continue connecting (yes/no)? yes

  • 输入 yes,提示如下

 

Warning: Permanently added 'qdjr.git.zhudb.com,121.43.184.183' (ECDSA) to the list of known hosts.
Welcome to GitLab, xxx!
  • 自此说明配置成功

总结

  • 首先我们建立了两个不同的文件夹来存放不同的ssh key
  • 通过config ,指定不同的 git 账号对应不同的 ssh key



作者:ifjgm
链接:https://www.jianshu.com/p/cacf91579268
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章