对不同的邮箱生成不同的 ssh key

生成密钥对

# 设置公司的
ssh-keygen -t rsa -C "[email protected]" -f ~/.ssh/gitlab_rsa
# 设置默认的,一般都是给 gitlab 用的
ssh-keygen -t rsa -C "[email protected]"
# 查看生成的密钥对
ls -la ~/.ssh
# -rw-------    1 genffy  staff  2610 Feb 15 17:48 gitlab_rsa
# -rw-r--r--    1 genffy  staff   578 Feb 15 17:48 gitlab_rsa.pub
# -rw-------    1 genffy  staff  2602 Feb 15 17:51 id_rsa
# -rw-r--r--    1 genffy  staff   571 Feb 15 17:51 id_rsa.pub

创建配置文件

vim .ssh/config

填入以下内容

# gitlab.orgname.com
Host gitlab.orgname.com
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/gitlab_rsa
  User [email protected]

# github.com
# Host github.com
#  AddKeysToAgent yes
#  UseKeychain yes
#  IdentityFile ~/.ssh/github_rsa
#  User [email protected]

测试设置效果

ssh -T [email protected]
# Hi genffy! You've successfully authenticated, but GitHub does not provide shell access.
ssh -T [email protected]
# Welcome to GitLab, @zhengfei.li!

配置不同的 git 目录使用不同的密钥

复制默认的 .gitconfig

cp .gitconfig .gitconfig-gitlab
cp .gitconfig .gitconfig-id

编辑不同的配置文件的 user 信息

vim .gitconfig-gitlab
[user]
	name = zhengfei.li
	email = zhengfei.li@orgname.com
	signingkey = ~/.ssh/gitlab_rsa.pub
[pull]
	rebase = false
[filter "lfs"]
	process = git-lfs filter-process
	required = true
	clean = git-lfs clean -- %f
	smudge = git-lfs smudge -- %f
[init]
	defaultBranch = main
[commit]
	gpgsign = true
[gpg]
	format = ssh
vim .gitconfig-id
[user]
	name = genffy
	email = genffyl@gmail.com
	signingkey = ~/.ssh/id_rsa.pub
[pull]
	rebase = false
[filter "lfs"]
	process = git-lfs filter-process
	required = true
	clean = git-lfs clean -- %f
	smudge = git-lfs smudge -- %f
[init]
	defaultBranch = main
[commit]
	gpgsign = true
[gpg]
	format = ssh

设置不同仓库目录使用不同 .gitconfig

vim .gitconfig
[includeIf "gitdir:~/workspace/"]
	path = .gitconfig-id
[includeIf "gitdir:~/Documents/workspace/"]
	path = .gitconfig-gitlab

最后可以在不同的目录下,修改下代码提交测试效果