1. 步驟
1.首先現在電腦端安裝好git,windows端請安裝Git for Windows,Linux端請自行網上查詢(Ubuntu: sudo apt-get install git)
2.先核對下電腦上是已經有ssh配置
#Git Bash on Windows / GNU/Linux / macOS / PowerShell: cat ~/.ssh/id_rsa.pub
3.若沒有,則需要生成ssh的公鑰私鑰
Git Bash on Windows / GNU/Linux / macOS:
##若要自定義id_rsa文件請先切換目錄到 ~/.ssh/下,如果不切換,當保存的文件名是自定義時,會生成在當前的目錄下。
##經測試,郵箱不一定是登錄gitlab的郵箱(我github也是用mygitlab@gitlab.com生成的id_rsa_pub作為公鑰)
ssh-keygen -t rsa -C your.email@example.com -b 4096
#提示是否使用新的文件名,如果不輸入新的文件名,則生成id_rsa文件。
##如果默認不配置config,就得默認為id_rsa文件名
Enter file in which to save the key (~/.ssh/id_rsa):
#請輸入確認密碼,后面還會用到(至少4位數),如果缺省直接按回車
##此密碼是驗證id_rsa的密碼,每次代碼commit時得輸入
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
4. 復制公鑰到GitLab中的SSH Keys中
Windows Command Line:
type %userprofile%\.ssh\id_rsa.pub | clip
Git Bash on Windows / Windows PowerShell:
cat ~/.ssh/id_rsa.pub | clip
如果提示clip沒安裝,則只要‘ |’ 的前半部分命令,然后復制出文本,或者直接到指定位置用文本打開。
5.測試SSH是否已配置好
ssh -T git@gitlab.com #如果已經配置好,則會提示 Welcome to GitLab, Your GitLab NickName!
6.
配置config文件(可選,當第5步驟失敗)
如果id_rsa是自己定義為id_rsa_custom的,才需要配置config,具體見參考[1]
在~/.ssh/下面新建一個文件
cd ~/.ssh/ touch config
config內容如下:
# GitLab.com server Host gitlab Hostname gitlab.com User git IdentityFile ~/.ssh/id_rsa_custom
ssh -T git@gitlab #如果已經配置好,則會提示 Welcome to GitLab, Your GitLab NickName!
7.Clone項目到本地
如果gitlab上已經有Repo(項目),則直接clone一份代碼到本地
#如果用SSH clone失敗了,請嘗試用HTTPS clone ##目前只在company的服務器ubuntu系統失效了 git clone git@gitlab.com:username/yourProject.git #(SSH方式) git clone https://gitlab.com/username/yourProject.git #(HTTPS方式) #此時會出現登錄gitlab的賬號和密碼的輸入,然后顯示進度條 Receiving objects: 86% (797/918), 2.48 MiB | 5.00 KiB/s
如果gitlab還沒有Repo,可以新建一個,再clone空項目下來。
按理說github設置SSH原理是完全相同的。
p.s.
如果git還沒有配置過用戶名和郵箱需要設置一下
##用戶名和郵箱名和賬號名沒有必然相關性,可以不一樣 ##我用github的賬號設置了user.email,然而gitlab照樣可以push數據 ##首次clone數據時有要求輸入該網站的賬號和密碼,可以理解git的配置是git的賬號和昵稱 git config --global user.name "Your Name" git config --global user.email your_email@gmail.com
2. 可能出現的情況
在windows系統下用git bash,在第5步驟,一直提示超時連接,不管是ssh還是https協議。(以上兩項暫時只出現在company的PC)