Git SSH Key生成

SSH Key是一种加密的公钥私钥对,用于身份验证。

使用Git通过SSH拉取远程仓库时,出现以下内容:

1
2
3
4
5
6
7
8
$ git clone git@******.com:********.git
Cloning into 'gk_vblog'...
git@******.com: Permission denied (publickey).
fatal: Could not read from remote repository.

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

这是因为Git需要SSH Key来验证身份,而你没有配置SSH Key。

  1. 首先,检查是否已有SSH Key。
1
2
3
4
5
ls -al ~/.ssh

// or
cd ~/.ssh
ls

如果存在id_rsa.pub文件,则说明已有SSH Key。

  1. 如果没有SSH Key,则生成SSH Key。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
ssh-keygen -t rsa -C "your_email@example.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): yes
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:******** ********
The key's randomart image is:
+---[RSA 3072]----+
| .. |
| . ..o.. |
| .. o oo= |
| .o * o.. |
| .. oS.+.. |
| o. ..+E.+oo |
|oo....o.oo=..o |
|..+. . .oo.=+ . |
|.o.. .o o... |
+----[SHA256]-----+

  1. 然后,将SSH Key添加到ssh-agent。
1
ssh-add ~/.ssh/id_rsa

如果出现"Could not open a connection to your authentication agent.",则说明没有安装SSH Key。请安装并配置SSH Key。

1
2
3
4
5
eval "$(ssh-agent -s)"

// 或者
eval `ssh-agent`

如果出现以下内容,则说明SSH Key添加成功:

1
2
3
4
ssh-add ~/.ssh/id_rsa

Identity added: /c/Users/Administrator/.ssh/id_rsa (***email***)

再次执行

1
ssh-add ~/.ssh/id_rsa
  1. 将SSH Key添加到GitHub上,以便Git通过SSH拉取远程仓库。
    步骤:Settings -> SSH and GPG keys -> New SSH Key -> Title -> Key -> Add SSH Key

查看公钥,以便复制到GitHub上。

1
2
cat ~/.ssh/id_rsa.pub

  1. 最后,测试SSH Key是否配置成功。
1
ssh -T git@github.com
  1. 如果出现以下内容,则说明配置成功。
1
Hi *! You've successfully authenticated, but GitHub does not provide shell access.