1 前言
近日,換了台新電腦。
今日,正要更新(git pull
)GitLab的源碼時,在配置(用戶名,郵箱,密碼git config --global -l
)完全無誤的情況下,卻報出如下錯誤:
$ git pull
git@10.0.5.16's password:
Permission denied, please try again.
git@10.0.5.16's password:
Permission denied, please try again.
git@10.0.5.16's password:
git@10.0.5.16: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
查了一下網友們的博客,可以無疑確定問題所在:
因新電腦的SSH密鑰與GitLab個人賬戶中的SSH公鑰匹配不上,導致遠程自動登錄失敗,遠程拉取Git代碼錯誤。
(PS: (由於新電腦,.ssh下根本就不存在私鑰))
經過搗鼓一翻,還真成!那么,現在記錄一下叭!
2 使用SSH遠程登錄GitLab
-
step0 打開Git Bash
-
step1 確認/配置 Git的用戶名和郵箱 無誤
$ git config --global user.name "u$er"
[更改全局用戶名]
$ git config --global user.email "yyyy@xxxx.com"
[更改全局用戶郵箱]
$ git config --global -l
user.name=u$er
user.email=yyyy@xxxx.com
- step2 切換到當前用戶主目錄的ssh目錄下
若提示 “ No such file or directory”,可在系統對應路徑下新建.ssh
文件夾即可mkdir ~/.ssh
。
$cd ~/.ssh
$ pwd
/c/Users/Johnny/.ssh
- step3 本地生成SSH通信的公鑰和私鑰
$ ssh-keygen -t rsa -C "yyyy@xxxx.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/Johnny/.ssh/id_rsa): 【Enter】
Enter passphrase (empty for no passphrase):
Enter same passphrase again: 【可輸入SSH密碼,也可不輸入。一旦輸入,以后git pull/push等操作時,均需輸入SSH密碼】
Your identification has been saved in /c/Users/Johnny/.ssh/id_rsa.
Your public key has been saved in /c/Users/Johnny/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:1UMiwerwehwfhiuwehdsvbk234vjsdv453k456IL567pqwgKexRitL2bkHN6+yhkJY yyyy@xxxx.com
The key's randomart image is:
+---[RSA 2048]----+
| ..o . |
| .o.+ |
| + .--o |
| . o .+ . |
| + . +S. |
|++o++ = + |
|@*E. .O+ . |
|B++o+.B.o |
|o. +++.. |
+----[SHA256]-----+
$ ll
total 6
-rw-r--r-- 1 Johnny 197121 1766 9月 10 19:25 id_rsa
-rw-r--r-- 1 Johnny 197121 403 9月 10 19:25 id_rsa.pub
這樣系統路徑下就生成了2個密鑰文件:id_rsa(私鑰,存在本地)和id_rsa.pub(公鑰,發放給客戶端,例如:GitLab個人賬戶中)
- step4 全文拷貝生成的SSH公鑰到GitLab中
$ clip < ~/.ssh/id_rsa.pub
【clip: 拷貝/剪切板命令】


- step5 驗證
$ ssh -T git@GitLabHostAddress
[方式1]
$ git pull
Enter passphrase for key '/c/Users/Johnny/.ssh/id_rsa': 【若之前設置了SSH密碼,則:此時需輸入正確的SSH密碼】
remote: Enumerating objects: 1468, done.
remote: Counting objects: 100% (1468/1468), done.
remote: Compressing objects: 100% (735/735), done.
remote: Total 1468 (delta 781), reused 1360 (delta 719)
Receiving objects: 100% (1468/1468), 10.93 MiB | 5.03 MiB/s, done.
Resolving deltas: 100% (781/781), completed with 95 local objects.
...
[方式2]