- 许多 Git 服务器都使用 SSH 公钥进行认证。 为了向 Git 服务器提供 SSH 公钥,如果某系统用户尚未拥有密钥,必须事先为其生成一份。 这个过程在所有操作系统上都是相似的。 首先,你需要确认自己是否已经拥有密钥。 默认情况下,用户的 SSH 密钥存储在其 ~/.ssh 目录下。 进入该目录并列出其中内容,你便可以快速确认自己是否已拥有密钥:
其中.pub后缀的是公钥(我这里是配置了两个),另外一个同名不带后缀的是私钥- 生成ssh密钥
ssh-keygen -t rsa -C "your_email@example.com"
代码参数含义:
-t 指定密钥类型,默认是 rsa ,可以省略。
-C 设置注释文字,比如邮箱。
-f 指定密钥文件存储文件名。
回车确认,会要求你输入保存密钥的位置以及使用密钥的口令,保持默认(回车)即可
Generating public/private rsa key pair.
Enter file in which to save the key (C:\Users\focus\.ssh\id_rsa):
Created directory 'C:\Users\focus\.ssh.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\focus\.ssh\id_rsa.
Your public key has been saved in C:\Users\focus\.ssh\id_rsa.pub.
The key fingerprint is:
d0:82:24:8e:d7:f1:bb:9b:33:53:96:93:49:da:9b:e3 your_email@example.com
如果有多个账户的话,可再次执行该操作,不过生成时候的文件名有所不同
ssh-keygen -t rsa -C "your_email2@example.com"
Generating public/private rsa key pair.
Enter file in which to save the key (C:\Users\focus\.ssh\id_rsa):C:\Users\focus\.ssh\id_github_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\focus\.ssh\id_github_rsa.
Your public key has been saved in C:\Users\focus\.ssh\id_github_rsa.pub.
The key fingerprint is:
d0:82:24:8e:d7:f1:bb:9b:33:53:96:93:49:da:9b:e3 your_email2@example.com
可同时看到两个文件
- 将密钥添加到ssh-agent的高速缓存中
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_github_rsa
- 展示已经添加的密钥
ssh-add -l
- 配置多个git账户
1.在指定的密钥生成文件夹目录下创建config文件,配置多个账户的git信息,若访问端口非默认的80端口,需要通过Port参数指定,否则将无法正常使用,区分公钥文件位置以及名称
#gitlab
Host github.app.cn
HostName github.app.cn
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_hd
Port 10080
#github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_github
# 配置文件参数
# Host : Host可以看作是一个你要识别的模式,对识别的模式,进行配置对应的的主机名和ssh文件
# HostName : 要登录主机的主机名
# User : 登录名
# IdentityFile : 指明上面User对应的identityFile路径
- 绑定密钥
这里配置了两个账户,但是绑定的方式大同小异
1.登陆到git网站,setting中绑定key,添加一个新key,将*.pub文件中内容复制进去
gitlab的绑定方式类似,不再赘述
绑定完成测试一下:
ssh -T git@github.com
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.
恭喜你,配置完成,尽情使用吧!