git配置多端多账号

前言

通过 git –version 命令,确认是否安装Git,显示当前安装的版本,则说明已安装。
为同一个设备,配置多个 git 账号,主要流程如下:

  1. 清空全局 user.name 和 user.email
  2. 为当前项目配置git用户名和邮箱
  3. 为不同的 git 账户生成不同的 ssh-key
  4. 将以上的 ssh-key 分别添加到 ssh-agent 信任列表
  5. 添加以上的公钥到自己的 git 账户中
  6. 在 config 文件配置多个 ssh-key
  7. 测试ceshiceeccee

1. 清空默认的全局 user.name 和 user.email

1
2
git config --global --unset user.name
git config --global --unset user.email

查看git配置: git config --global --list

2、配置多个git的用户名和邮箱

a、单个配置

1
2
git config --global user.name "yourusername"
git config --global user.email "youremail@email.com"

b、多个配置

注意: 这里git config命令没有带—global,表示这是一个局部的设置,也就是这个用户是当前项目的,而不是全局的。

1
2
git config user.name "yourusername"
git config user.email "youremail@gitee.com"

c、删除配置

1
2
git config --unset user.name
git config --unset user.email

3、生成多个密钥

生成SSH秘钥对

指定文件路径,方便后面操作:~/.ssh/id_rsa_gitee,id_rsa_github是秘钥的别名。

1
2
ssh-keygen -t rsa -f ~/.ssh/id_rsa_gitee -b 4096 -C "youremail@gitee.com"
ssh-keygen -t rsa -f ~/.ssh/id_rsa_github -b 4096 -C "youremail@github.com"

4、将 ssh-key 分别添加到 ssh-agent 信任列表

1
2
3
ssh-agent -s
ssh-add ~/.ssh/id_rsa_gitee
ssh-add ~/.ssh/id_rsa_github

如果看到 Identitiy added: ~/.ssh/id_ras_github,就表示添加成功了。

5、添加公钥到自己的 git 账户中

打开文件复制,带 pub 的文件即copy公钥,如id_rsa_gitee.pub、id_rsa_github.pub,复制到到 git 账户中粘贴即可

6、在 config 文件配置多个 ssh-key

在生成密钥的.ssh 目录下,新建一个config文件,然后配置不同的仓库
(这是配置不同平台账号,同一平台多账号,直接看进阶配置)

1
2
3
4
5
6
7
8
9
10
11
12
13
#gitHub的配置
Host github.com
HostName github.com
User github
IdentityFile ~/.ssh/id_rsa_github

# gitee的配置
host gitee.com # 别名,最好别改
Hostname gitee.com #要连接的服务器
User gitee #用户名
#密钥文件的地址,注意是私钥
IdentityFile ~/.ssh/id_rsa_gitee

7、测试

1
2
ssh -T git@gitee.com
ssh -T git@github.com

8、进阶配置

当同一平台多账号时,编辑~/.ssh/config文件,host需配置不同的别名,且添加远程仓库时,也需要使用别名,否则会找不到对应的密钥,报权限问题。

  • 配置config文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # 配置第一个GitHub账号
    Host github-first
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_first

    # 配置第二个GitHub账号
    Host github-second
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_second
  • 项目文件中添加对应别名的远程仓库
    1
    2
    3
    4
    5
    # 使用第一个GitHub账号克隆仓库
    git clone git@github-first:username/repo.git

    # 使用第二个GitHub账号克隆仓库
    git clone git@github-second:username/repo.git
  • 测试
    1
    2
    ssh -T git@github-first
    ssh -T git@github-second
    tips:
  1. 测试通过了,但是提交代码,但是提交的时候还是要求输入用户名和密码。
    1
    把remote的地址https开头的换成git开头