技术笔记互联网如何为Git创建SSH Key

今天尝试从BitBucket通过SSH下载项目,发现下载失败报如下错误:

git@bitbucket.org: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights

原来是本机没有设置SSH Keys给BitBucket,立即创建一个。

1.首先可以通过命令测试一下是否连接成功:

> ssh -T git@bitbucket.org
git@bitbucket.org: Permission denied (publickey). // 报错显示无权限

2.接下来创建密钥。

> ssh-keygen -t rsa -C "youremailname@gmail.com"

添加命令参数-f othername,可以自定义存放密钥的文件名,如:ssh-keygen -t rsa -C “youremail@gmail.com” -f 。

可以通过-h查看更多命令参数的使用,如:ssh-keygen -h。

默认情况下,命令会在/Users/yourusername/.ssh/目录下创建id_rsa和id_rsa.pub两个文件。id_rsa存的是私钥,id_rsa.pub存的是公钥。

(base) yourname@Mac BitBucket % ssh-keygen -t rsa -C "youremailname@gmail.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/yourname/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/yourname/.ssh/id_rsa
Your public key has been saved in /Users/yourname/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:hpGRCvxfRqPcHUhhuCWzcVkQI3YuV821QzL7B7/e0aE youremailname@gmail.com
The key's randomart image is:
+---[RSA 3072]----+
| .    ++OBooo.o  |
|  o  .*BBo. o= . |
|   o o+%oo .. +  |
|    o ==+ .  . + |
|     ..oS     ..o|
|      ..      ..+|
|             E o.|
|              . o|
|               ..|
+----[SHA256]-----+

接下来将id_rsa.pub文件中的公钥内容拷贝到BitBucket, Bitbucket 操作界面 最后用命令测试一下是否连接成功。出现以下提示表示连接成功。

> ssh -T git@bitbucket.org
authenticated via ssh key.

You can use git to connect to Bitbucket. Shell access is disabled

接下来就可以从BitBucket通过SSH下载项目了。