配置ssh连接git

发布时间 2023-04-18 09:48:47作者: 时间在哪
在学习GitHub上的开源代码时,为了方便经常需要通过git从github克隆代码,如果是首次从github克隆代码时经常会碰到下面的提示:
Warning: Permanently added 'github.com,20.205.243.166' (ECDSA) to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

由提示可知这个主机没有权限从 github 克隆代码。

解决办法很简单,只需要几个操作就可以搞定:

1. 查看ssh密钥

首先通过以下命令查看自己机器上的当前用户是否有ssh密钥:
# ls -l ~/.ssh
total 12
-rw-------. 1 root root 1679 Feb 27 03:03 id_rsa
-rw-r--r--. 1 root root  392 Feb 27 03:03 id_rsa.pub
-rw-r--r--. 1 root root  370 Feb 27 02:42 known_hosts

如果能看到id_rsa.pub文件(或者以.pub结尾的文件),则说明已经存在ssh密钥,那么直接按照步骤3操作就行。如果没有看到这个文件,说明不存在ssh密钥。那么需要按照步骤2先生成密钥文件。

2. 创建ssh密钥

在命令行终端输入下面的命令:
ssh-keygen -C "github.com"
-C,指定对这个key的注释。
上述命令省略了几个选项:-t,指定key的类型,默认是RSA;
            -b,指定key的bits,默认是2048bits;
            -f,指定密钥文件名,默认是id_rsa;

然后会提示让你输入一些命令,为了简单,可以什么都不输入,只需要在提示输入的时候敲回车键即可:

Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:oylwjwjeoxywRHZ8/NzCVLgDZihGlh83VQ3Lpfatg3s github.com
The key's randomart image is:
+---[RSA 2048]----+
|     . .     .ooo|
|    . . +   o. +.|
|     o + * o .=  |
|    . o * o o. ..|
|. . .o oSo +    o|
|...+oo.o..= o. . |
| o.oo.+    =..o  |
|o o +.      ..E. |
|.. . .      ..   |
+----[SHA256]-----+

这样便代表密钥生成成功。

 3. 将密钥添加到github账户

在命令行终端输入:
vi ~/.ssh/id_rsa.pub

将文件中的内容全部复制。点击github右上侧头像,在下拉选项中点击Settings:

  在刷新后的页面中,点击红框1会出现红框2描述的按钮,接着点击红框2:

  然后又会出现新的内容:

  这次在title中输入一些描述,在key中输入刚刚复制的密钥文件的内存,然后点击"Add SSH key",就在github添加密钥完毕。最后再测试下权限是否添加成功。

4. 测试密钥是否添加成功

输入以下命令测试密钥是否添加成功:
# ssh -T git@github.com
Hi citta! You've successfully authenticated, but GitHub does not provide shell access.

如果见到上述提示,则说明添加成功,可以从github克隆代码了。