一,背景
- 工作代码在gitlab,自己的代码在github,需要在同时获得两个仓库的权限,需要在本地生成两个密匙,一般的方法会覆盖之前生成的密匙。
二,解决方法
- 首先查看本地是否有git,这里用mac展示
- 如果已经有 id_rsa.pub 或者其他以 .pub 结尾的公钥文件,你可以选择使用这些已有的密钥或创建新的。
ls -al ~/.ssh
- 创建新的SSH key
- 给github创建SSH key,命名为id_rsa_github
ssh-keygen -t rsa -b 4096 -C "your_github_email@example.com" -f ~/.ssh/id_rsa_github
- 给gitlib创建SSH key,命名为id_rsa_gitlab
ssh-keygen -t rsa -b 4096 -C "your_gitlab_email@example.com" -f ~/.ssh/id_rsa_gitlab
- 添加SSH key到ssh-agent:
- ssh-agent是记住你的密码和管理keys,将它们添加到ssh-agent。
- 首先确保ssh-agent正在运行:
注:重启电脑ssk-agent进程会关闭,需要重新运行
eval "$(ssh-agent -s)"
- 接着,添加新生成的SSH keys到ssh-agent:
ssh-add -K ~/.ssh/id_rsa_github
ssh-add -K ~/.ssh/id_rsa_gitlab
- -K选项是Mac特有的,用于将密钥的密码添加到钥匙串(Keychain)中。
- 然后将生产的密匙分别添加到对应的仓库
- 就是复制~/.ssh/id_rsa_github.pub的内容,粘贴到github->SSH and GPG keys里,新建个SSH key即可
- 本地继续配置SSH config文件,为了让git知道如何使用SSH key
touch ~/.ssh/config
open -e ~/.ssh/config
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_rsa_gitlab
- 配置好以上操作,本地两个密匙才能同时生效