Skip to content

1、查看全局配置

cmd
    git config --global --list

如果其中有 user.name 和 user.email 信息,请执行以下命令将其清除掉:

cmd
    git config --global --unset user.name
    git config --global --unset user.email

2、生成公钥和私钥

将命令行,切换到ssh目录

cmd
    cd ~/.ssh

生成github、GitLab或Gitee的公钥、私钥

cmd
    ssh-keygen -t rsa -C "这里是备注,推荐备注邮箱或名称"

按下 ENTER 键后,会有输入名称的提示,默认是id_rsa,可以根据平台或用户名命名不同的名字,例如id_rsa_github,id_rsa_gitee等 生成后在文件夹~/.ssh下会生成id_rsa文件,带后缀.pub的是公钥,另一个是私钥

3、在git对应平台上配置ssh公钥

将生成的公钥使用记事本打开,将内容复制配置到对应仓库的ssh配置中;

4、在本地添加私钥

配置几个就可以添加几个

cmd
    ssh-add ~/.ssh/id_rsa

如果报错:Could not open a connection to your authentication agent. 先运行

cmd
    ssh-agent bash

5、密钥管理

通过以上步骤,公钥、密钥分别被添加到 git 服务器和本地了。下面我们需要在本地创建一个密钥配置文件,通过该文件,实现根据仓库的 remote 链接地址自动选择合适的私钥。 编辑 ~/.ssh 目录下的 config 文件,如果没有,就需要创建。

text
# Host 别名,建议和HostName设置一样
Host github
# HostName 仓库域名
HostName github.com
# User 用户名
User userGithub
# IdentityFile 私钥
IdentityFile ~/.ssh/id_rsa_github

Host gitee
HostName gitee.com
User userGitee
IdentityFile ~/.ssh/id_rsa_gitee

6、验证配置是否正确

cmd
    ssh -T git@github.com

7、仓库配置

git 的配置分为三级别,System —> Global —>Local。System 即系统级别,Global 为配置的全局,Local 为仓库级别,优先级是 Local > Global > System。

因为我们并没有给仓库配置用户名,又在一开始清除了全局的用户名,因此此时你提交的话,就会使用 System 级别的用户名,也就是你的系统主机名了。

因此我们需要为每个仓库单独配置用户名信息,假设我们要配置 github 的某个仓库,进入该仓库后,执行:

cmd
    git config --local user.name "用户名"
    git config --local user.email "邮箱"
最近更新