Git 是分布式的代碼管理工具,本地 Git 倉庫和 GitHub 倉庫之間的傳輸是通過 SSH 加密的,因此需要配置 SSH。
Git 支持多種協(xié)議,包括 https,但通過SSH支持的原生 Git 協(xié)議速度最快,并且提交代碼時不需要每次輸入用戶名密碼。
- 創(chuàng)建 SSH keys
在用戶主目錄下,查找是否存在.ssh目錄,若存在,再看看這個目錄下有沒有 id_rsa 和 id_rsa.pub 這兩個文件,如果已經(jīng)有了,可直接跳到下一步。如果沒有,執(zhí)行以下命令創(chuàng)建 SSH keys:
ssh-keygen -t rsa -C "youremail@example.com"
接下來一直回車,使用默認值即可,無需自己設置密碼。如令執(zhí)行成功后,可以在用戶主目錄里找到 .ssh目錄,里面有 id_rsa 和 id_rsa.pub 兩個文件,這兩個就是 SSH Key 的密鑰對,id_rsa 是私鑰,不能泄露出去,id_rsa.pub 是公鑰,可以告訴其他人,效果圖如下所示:
anyang@anyang:~/anyang/learngit$ cd ~
anyang@anyang:~$ ssh-keygen -t rsa -C "xautanyang@163.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/anyang/.ssh/id_rsa):
Created directory '/home/anyang/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/anyang/.ssh/id_rsa.
Your public key has been saved in /home/anyang/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:7atG/8A6Zm5+CFNDwLA0KBFrKB512Z08gWtD15gGYPk xautanyang@163.com
The key's randomart image is:
+---[RSA 2048]----+
|oo o+*o=. |
|o.o.o=.+.X . |
|++ . o.+ . |
|+ . Eo. |
| . ..S.. |
| o .o |
| + o+ |
| B.oo |
| B=+... |
+----[SHA256]-----+
anyang@anyang:~$ cd .ssh/
anyang@anyang:~/.ssh$ ls
id_rsa id_rsa.pub
- 登陸 GitHub,打開“Settings”頁面,切換到“SSH and GPG keys”標簽頁,點擊“New SSH key”,輸入Title(自己起名)和 key(id_rsa.pub 文件的內(nèi)容),點擊“Add SSH key”即可,如下所示:

SSH key 能夠幫助 GitHub 識別出提交內(nèi)容是否是所屬用戶提交的,而不是別人冒充的,這樣有效地提高了遠程倉庫的安全性。GitHub 允許添加多個 Key,從而實現(xiàn)單用戶多處提交功能。
- 輸入以下內(nèi)容進行測試:
ssh git@github.com
若輸出信息如下所示,則配置成功。
Warning: Permanently added the RSA host key for IP address '192.30.253.112' to the list of known hosts.
PTY allocation request failed on channel 0
Hi anyang! You've successfully authenticated, but GitHub does not provide shell access.
Connection to github.com closed.
相關資料:
- Git 官網(wǎng)
- Git 官方文檔
- [廖雪峰的 Git 教程](http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8
067c8c017b000) - Git 常用命令查詢文檔
- Git 在線學習網(wǎng)址