GitHub添加SSH key

1.打开Git Bash命令行窗口

2.检查是否已有SSH

如果没有,会返回如下信息,继续第三步创建SSH

1
2
$ cd ~/.ssh
bash: cd: /c/Users/Him/.ssh: No such file or directory

Click and drag to move

如果本地已经有创建SSH,会返回如下信息,表示本地已经有创建过SSH了,跳过第三步,直接看第四步

1
2
3
4
$ cd ~/.ssh

$ ls
id_rsa id_rsa.pub known_hosts

Click and drag to move

3.创建SSH key

最后一个参数替换成你自己的GitHub注册邮箱

1
2
$ ssh-keygen -t rsa -C "your_email@example.com"
Generating public/private rsa key pair.

Click and drag to move

接下来会提示你输入生成的key存放的路径,不设置直接回车的话会默认创建在C:/Users/你的用户账号/.ssh文件夹下

1
2
Enter file in which to save the key (/c/Users/Him/.ssh/id_rsa):
Created directory '/c/Users/userpath/.ssh'.

Click and drag to move

再接下来会提示你输入密码,这个密码是用来每次提交的时候输入确认,可以不设置,直接回车两次

1
2
Enter passphrase (empty for no passphrase):
Enter same passphrase again:

Click and drag to move

最后成功后会看到类似如下的输出,表示成功生成SSH key了,可以到C:/Users/你的用户账号/.ssh文件夹下看下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Your identification has been saved in /c/Users/Him/.ssh/id_rsa.
Your public key has been saved in /c/Users/Him/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:RwvBINgH8CEt2KniltmykeyDsOseUYcwMzehFeyT86s 1225723686@qq.com
The key's randomart image is:
+---[RSA 2048]----+
| o+%OO+o. |
|..=+%*+ .. |
| ..+o+o.. . |
|o. o=. o . |
|o oolalala S o |
| +.+.. . . |
|. .o . |
| . . . |
| . E. |
+----[SHA256]-----+

Click and drag to move

4.添加SSH key到GitHub

首先复制.ssh文件夹下id_rsa.pub文件的内容,可以直接用文本编辑器打开复制,也可以用如下命令行复制

1
$ clip < ~/.ssh/id_rsa.pub

Click and drag to move

然后进入https://github.com/settings/keys设置,如果没有登录要先登录

或者登录后依次点击右上角Settings,然后再点击SSH and GPG keys

然后点击New SSH key按钮,然后输入Title和我们刚才复制的Key,Title的话表示这个key来自哪里,比如说可以叫“家里的笔记本”

最后点击Add SSH key按钮保存

5.测试SSH连接

输入如下命令

1
$ ssh -T git@github.com

Click and drag to move

会得到如下输出,询问是否确认连接,输入yes回车确认

1
2
3
The authenticity of host 'github.com (13.229.188.59)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJWGl7mykeyCspRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)? yes

Click and drag to move

最后连接成功会看到如下输出

1
2
Warning: Permanently added 'github.com,13.229.188.59' (RSA) to the list of known hosts.
Hi ghxiaoxiao! You've successfully authenticated, but GitHub does not provide shell access.

Click and drag to move

参考