1. 程式人生 > 實用技巧 >[Git/GitLab]使用SSH遠端登入GitLab/GitHub

[Git/GitLab]使用SSH遠端登入GitLab/GitHub

1 前言

近日,換了臺新電腦。
今日,正要更新(git pull)GitLab的原始碼時,在配置(使用者名稱,郵箱,密碼git config --global -l)完全無誤的情況下,卻報出如下錯誤:

$ git pull
[email protected]'s password:
Permission denied, please try again.
[email protected]'s password:

Permission denied, please try again.
[email protected]'s password:
[email protected]: 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個人賬戶中的公鑰匹配不上,導致遠端自動登入失敗,遠端拉取Git程式碼錯誤。

經過搗鼓一翻,還真成!那麼,現在記錄一下叭!

2 使用SSH遠端登入GitLab

  • step0 開啟Git Bash

  • step1 確認/配置 Git的使用者名稱和郵箱 無誤

$ git config --global user.name "u$er"
 [更改全域性使用者名稱]
$ git config --global user.email "[email protected]"
 [更改全域性使用者郵箱]

$ git config --global -l
user.name=u$er
[email protected]
  • step2 切換到當前使用者主目錄的ssh目錄下
    若提示 “ No such file or directory”,可手動在系統對應路徑下新建.ssh資料夾即可。
    再輸入 mkdir ~/.ssh 回車,進入.ssh路徑下。
$cd ~/.ssh

$ pwd
/c/Users/Johnny/.ssh
  • step3 本地生成SSH通訊的公鑰和私鑰
$ ssh-keygen -t rsa -C "[email protected]"
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 [email protected]
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]

X 參考文獻