重装系统后重新关联 GitHub

重装系统后, 系统盘文件都会被清空,会删除 .ssh 目录下绑定好的 ssh 公钥和私钥,此时 git push 本地仓库,便会报错:

1
2
3
4
5
6
$ git push
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

对此,需要本地重新关联 GitHub 账号,才能继续 push 本地仓库。

本地创建 ssh key

在命令行窗口输入 ssh-keygen -t rsa -C "your_email@youremail.com",这里要将 your_email@youremail.com 改为自己指定的邮箱。然后,敲三次回车,就生成了 ssh key。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ ssh-keygen -t rsa -C "liupaopao520@163.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/Administrator/.ssh/id_rsa
Your public key has been saved in /c/Users/Administrator/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:v9WQpeyCOJKOJG2vKrCbFfKnIo7tbFnZ4Qnp8LVSU2E liupaopao520@163.com
The key's randomart image is:
+---[RSA 3072]----+
| E. |
| .. |
| . . . |
| . o = . + |
|*Oo* . . + |
|OBB.o . |
+----[SHA256]-----+

生成的 ssh key 文件位于 C:\Users\Administrator\.ssh 目录下,打开 id_rsa.pub,复制里面的公钥。

1
2
3
4
5
6
7
8
$ pwd
/c/Users/Administrator/.ssh

$ ls
id_rsa id_rsa.pub known_hosts

$ cat id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDEy......l8xl8s8VEc= liupaopao520@163.com

GitHub 添加 ssh key

进入 GitHub 网站,进入 Account Settings,左边选择 SSH and GPG keys,然后在 SSH keys 分类里,点击 New SSH keys,Title 随便填,粘贴刚才复制的 Key。

打开 git bash,输入 ssh -T git@github.com,验证是否关联成功。看到如下信息,则说明已成功关联 GitHub。

1
2
$ ssh -T git@github.com
Hi HanxuLiu! You've successfully authenticated, but GitHub does not provide shell access.