注意:全程使用git自带的命令行工具git bash
新创建一个public key
假设之前电脑上已经配置过了一次git ssh(在~/.ssh目录下),通过下边命令创建一个新的key。
$ ssh-keygen -t rsa -C “your_email@youremail.com”
注意在输入命令敲回车后会提示让你指定文件名,这时候我们不要用默认的,否则会覆盖现在已有的密钥文件。我们指定一个新的文件名,我这里是id_rsa_github
Enter file in which to save the key (/c/Users/lismo/.ssh/id_rsa): /c/Users/lismo/.ssh/id_rsa_github
这时候检查~/.ssh目录,应该至少有四个文件,分别是:
- id_rsa
- id_rsa.pub
- id_rsa_github
- id_rsa_github.pub
把新生成的key关联到github
在github上把新生成的SSH key添加进去,这步同之前添加SSH key的操作一样。进入github->Your Profile,左侧点击SSH and GPS keys,然后点击New SSH key。
添加到SSH认证代理
在本地通过下边的命令
$ ssh-add ~/.ssh/id_rsa_github
有的可能会有报错,提示“Could not open a connection to your authentication agent.”,这是因为你没有开SSH认证代理造成的,先执行如下命令,然后再添加
eval $(ssh-agent)
成功了会有如下提示
Identity added: /c/Users/lismo/.ssh/id_rsa_github (your_email@youremail.com)
创建config文件
我们需要告诉git每个key都在什么情况下需要用到。在~/.ssh/目录下创建config文件,也可以通过下边命令创建
$ touch ~/.ssh/config
打开config文件,写入如下内容
#gitlab
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_rsa
#github
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
测试
现在可以通过git clone从新配置的github上克隆下代码试试看配置是否成功。