拉去远端仓库代码一般包括 HTTPS
和 SSH
两种方式.
如果为 非公开仓库 使用 HTTPS
时候每次都要输入密码, 比较繁琐. 因此使用 SSH
的方式就比较方便了.
使用 SSH 公钥还可以让你在你的电脑和 远端
Git
通讯的时候使用安全连接(Git 的 Remote 要使用 SSH 地址) 像[email protected]:xxxxxx/xxxxxx.git
的类似形式
生成 SSH KEY
执行如下命令:
1
$ ssh-keygen -t rsa -C "[email protected]"
接下来会有如下提示:
1
2
3
4
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxxxx/.ssh/id_rsa): filename # 文件名
Enter passphrase (empty for no passphrase): # 输入密码 (可以直接回车不设置)
Enter same passphrase again: # 再次输入密码
最终控制台打印结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Your identification has been saved in gitee.
Your public key has been saved in gitee.pub.
The key fingerprint is:
SHA256:OO+WGxpm62Eo+WvelRkaouGNBybn/w3z/kFADlCSWJs [email protected]
The key's randomart image is:
+---[RSA 3072]----+
| o++o . |
| . .+ + |
| E o |
| . . |
|. = . + S . |
| * B o = = |
| B + X *.. |
| =.= %o. . |
| o=+*o*o. |
+----[SHA256]-----+
之后就会生成 filename
(私钥) 和 filename.pub
(公钥) 两个文件.
添加 SSH KEY 到 Git 远端
我们常用的第三方平台有: Github
Gitee
Coding
Gitlab
等.
添加方法都基本一致:
设置
->SSH 公钥
.- 填入
标题
和公钥
. - 一般还会验证
平台登录密码
, 成功后即可成功添加.
公钥
可以直接用文本编辑工具打开, 直接 全部复制 获得
添加 SSH KEY 至 ssh-agent
以上步骤完成之后大概率 git clone
也就会报错:
1
2
3
Cloning into 'repository'...
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.
执行如下命令:
1
2
3
ssh-add ./filename # 此处为文件路径
Enter passphrase for ./filename: # 输入密码
Identity added: ./filename ([email protected]) # 添加成功
因为控制台当前路径在
.ssh
目录下, 因此路径为./filename
此处输入的密码为创建ssh key
时候的密码
尝试执行 git clone
命令
1
2
3
4
5
6
7
8
$ git clone [email protected]:xxxxxx/repository.git
Cloning into 'repository.'...
remote: Enumerating objects: 405, done.
remote: Counting objects: 100% (405/405), done.
remote: Compressing objects: 100% (340/340), done.
remote: Total 405 (delta 101), reused 213 (delta 18), pack-reused 0
Receiving objects: 100% (405/405), 14.16 MiB | 4.62 MiB/s, done.
Resolving deltas: 100% (101/101), done.
仓库成功拉到本地.