一台电脑配置多个git账号

483 阅读2分钟

工作使用gitlab账号,自己学习使用github账号,在公司只有一台电脑,可以考虑配置多个Git账号,只需要通过SSH Key配置多个公钥就可以实现

配置SSH Key

  • 1.清空全局的邮箱和用户名称
 git config --global unset user.name
 git config --global unset user.email
  • 2.打开终端,在主目录下创建.ssh文件夹
   touch ~/.ssh
  • 3.根据邮箱,生成邮箱账号对应的密钥
 // github 的ssh,邮箱填github的注册邮箱,在主目录下会生成对应的私钥(id_rsa)和公钥(id_rsa.pub)
    ssh-keygen -t rsa -C "github注册邮箱" -f ~/.ssh/id_rsa
 // gitlab 的ssh,邮箱填gitlab的注册邮箱,在主目录下会生成对应的私钥(id_rsa_work)和公钥(id_rsa_work.pub)
    ssh-keygen -t rsa -C "gitlab注册邮箱" -f ~/.ssh/id_rsa_work
 // 若添加成功,则默认会打印出两个邮箱对应的配置信息
  • 4.此时查看.ssh目录,下有4个文件,而git默认只使用id_rsa,我们需要将两个密钥添加进去
   ssh-agent bash
   ssh-add  ~/.ssh/id_rsa
   ssh-add ~/.ssh/id_rsa_work
   ssh-add -l
  • 5.在.ssh中新建config配置文件
  cd ~/.ssh
  touch config
  • 6.,添加配置信息,让git根据不同的域名,使用不同的密钥(每个密钥对应不同git邮箱账号)
  # 账号1 -github
  HOST github.com #github的别名,测试时直接访问该地址即可
  Hostname github.com #github真实地址
  User yourgithubname  #github用户名 -请填写自己的用户名
  IdentityFile ~/.ssh/id_rsa #github私钥文件路径
  PreferredAuthentications publickey #首选认证方式



  # 账号1 -gitlab
  HOST gitlab.com
  Hostname gitlab.mob.com #gitlab真实地址- 请填写自己使用的真实地址
  User yourgitlabname #-请填写自己的用户名
  IdentityFile ~/.ssh/id_rsa_work
  PreferredAuthentications publickey #首选认证方式
    1. 分别在github 和 gitlab上添加公钥 ,分别为 (id_rsa.pub)的内容 和(id_ras_work.pub) 以github为例:步骤:登陆账号--->点击头像---->settings--->SSH and GPG keys --->New SSH key—>填写titleKeytitle:可随意填写,相当于给SSH Key取一个别名,Key就是将公钥内容复制进来)
    1. 测试
// 测试github连接
  ssh -T git@github.com
  ssh -T git@gitlab.com

若此时出现

  The authenticity of host 'github.com (20.205.243.166)' can't be established.

  ED25519 key fingerprint is SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU.

  This key is not known by any other names

  Are you sure you want to continue connecting (yes/no/[fingerprint])?

输入yes即可 出现 Hi XXX! You've successfully authenticated, but GitHub does not provide shell access.表示连接成功

  • 9. 在对应的项目名称下设置对应的用户名及邮箱即可
    • 找到项目所在目录下的 .git,进入.git文件夹,然后执行如下命令分别设置用户名和邮箱
 git config user.email "youremail"
 git config user.name "yourname"