git 多账户配置

环境 MacOS

  • 检查是否已有全局账户设置:
$ git config --global user.name
$ git config --global user.email

如果都没有返回值,就说明没有已配置的 git 账户,否则请删除账户信息:

$ git config --global --unset user.name "yourname"
$ git config --global --unset user.email "youremail"
  • 生成公钥和秘钥
$ ssh-keygen -t rsa -C "your_email1"
$ ssh-keygen -t rsa -C "your_email2"

注意 生成过程中的 Enter file in which to save the key (/Users/faremax/.ssh/id_rsa): 一步骤请分别起不同的名。

查看生成的文件:

ls -l ~/.ssh
-rw-------  1 faremax  staff  1679  7  6 11:05 id_rsa_github
-rw-r--r--  1 faremax  staff   400  7  6 11:05 id_rsa_github.pub
-rw-------  1 faremax  staff  1679  7  6 11:06 id_rsa_gitlab
-rw-r--r--  1 faremax  staff   405  7  6 11:06 id_rsa_gitlab.pub
-rw-r--r--  1 faremax  staff   602 12  6  2017 known_hosts

忽略2017年创建的几个文件,可以看到两个不同的公钥和私钥对已经生成成功了。

  • 分别在 GitHub 和 Gitlab 中录入对应的公钥
$ pbcopy < id_rsa_github.pub   # 复制文件内容

《git 多账户配置》

$ pbcopy < id_rsa_gitlab.pub

《git 多账户配置》

  • 添加并识别私钥
$ ssh-agent bash
$ ssh-add ~/.ssh/id_rsa
$ ssh-add ~/.ssh/id_rsa_github
$ ssh-add ~/.ssh/id_rsa_gitlab
  • 创建配置文件
$ touch ~/.ssh/config

在该文件中添加以下配置

#该文件用于配置私钥对应的服务器
#Default gitlab user(email1@hostname.com)
 Host git@hostname.com
 HostName https://hostname.com
 User git
 IdentityFile ~/.ssh/id_rsa_gitlab
######################################
#Add github user(email1@hostname.com)
 Host git@github.com
 HostName https://github.com
 User git
 IdentityFile ~/.ssh/id_rsa_github
  • 验证连接Git

以下输入输出表示链接成功,如果提示权限问题,说明秘钥和公钥匹配除了问题,请检查并重复上述步骤(使用 -vT 参数执行下面命令查看错误信息)

$ ssh -T git@github.com
Hi faremax! You've successfully authenticated, but GitHub does not provide shell access.
$ ssh -T git@hostname.com
Welcome to GIT, faremax!
    原文作者:Faremax
    原文地址: https://segmentfault.com/a/1190000016330457
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞