日常使用 git 作为仓库使用时,会遇到以下情况:
- 有两个 github 账号(至少两个),一台电脑同时连接这两个账号进行维护
- 私人 github 账号,公司 gitlab 账号
1 清除 git 的全局设置(针对已安装 git)
新安装 git 跳过。
若之前对 git 设置过全局的 user.name 和 user.email。类似(用git config --global --list 进行查看你是否设置)
$ git config --global user.name "你的名字" $ git config --global user.email "你的邮箱"
必须删除该设置
$ git config --global --unset user.name "你的名字" $ git config --global --unset user.email "你的邮箱"
2 生成新的 SSH keys
(1)#GitHub的钥匙
ssh-keygen -t rsa -C "[email protected]"
Enter file in which to save the key (/Users/kingboy/.ssh/id_rsa): /Users/kingboy/.ssh/ github_id_rsa
(2)#gitlab
ssh-keygen -t rsa -C "[email protected]"
Enter file in which to save the key (/Users/kingboy/.ssh/id_rsa): /Users/kingboy/.ssh/ gitlab_id_rsa
注意:输入的是钥匙的位置和名称。github和gitlab是不同的。
(3)完成后会在~/.ssh/目录下生成以下文件:
- github_id_rsa
- github_id_rsa.pub
- gitlab_id_rsa
- gitlab_id_rsa.pub
3 添加识别 SSH keys 新的私钥
默认只读取 id_rsa,为了让 SSH 识别新的私钥,需要将新的私钥加入到 SSH agent 中
$ ssh-agent bash $ ssh-add ~/.ssh/github_id_rsa $ ssh-add ~/.ssh/gitlab_id_rsa
4 多账号必须配置 config 文件
若无 config 文件,则需创建 config 文件
$ touch ~/.ssh/config # 创建config文件
config 里需要填的内容
#Default gitHub user Self Host github.com HostName github.com User git IdentityFile ~/.ssh/github_rsa #Add gitLab user Host [email protected] HostName http://git.startdt.net User git IdentityFile ~/.ssh/lab_rsa
5 在github和gitlab网站添加ssh
6 测试是否连接成功
# 测试github $ ssh -T [email protected] # 测试gitlab $ ssh -T [email protected]