如何在GitHub中添加SSH key

使用GitHub托管项目时,经常要clone, push等等,需要添加SSH方便操作,具体方法如下

检查电脑是否已经有SSH key

1
$ cd ~/.ssh

检查.ssh是否存在id_rsa.pub和id_dsa.pub,两个文件。如果存在不需要重新生产,可跳过下一步骤。

生产SSH key

1
$ ssh-keygen -t rsa -C "user_email@example.com"

-t 指定密钥类型,默认是RSA,可以略去 -C 设置注释文字,这里用到的是邮箱 -f 指定文件储存的文件名

上述代码省略-f,因此运行后会提示输入文件名保存生成的文件

1
2
Generating public/private rsa key pair.
# Enter file in which to save the key (/c/Users/you/.ssh/id_rsa): [Press enter]
这时回车,使用默认文件名

然后会提示设置密码,这个密码主要用于push文件。如果不输入密码,直接回车,之后push时就不需要输入密码

1
2
Enter passphrase (empty for no passphrase):
# Enter same passphrase again:
之后显示如下代码:
1
2
3
4
Your identification has been saved in /c/Users/user/.ssh/id_rsa.
# Your public key has been saved in /c/Users/user/.ssh/id_rsa.pub.
# The key fingerprint is:
# 01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db user_email@example.com

添加到GitHub

复制id_rsa.pub文件的内容,添加到指定位置即可

测试SSH key

打开Git bash

输入

1
$ ssh -T git@github.com

可能出现如下内容

1
2
3
The authenticity of host 'github.com (192.30.252.1)' can't be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)?

这时只需要输入yes即可,会看到如下提示信息:

1
2
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.