如何生成SSH key
SSH key提供了一種與GitHub通信的方式,通過這種方式,能夠在不輸入密碼的情況下,將GitHub作為自己的remote端服務(wù)器,進(jìn)行版本控制
步驟
- 檢查SSH keys是否存在
- 生成新的ssh key
-
將ssh key添加到GitHub中
gevin-essay-how-to-generate-SSH-key.png
1. 檢查SSH keys是否存在
輸入下面的命令,如果有文件id_rsa.pub
或 id_dsa.pub
,則直接進(jìn)入步驟3將SSH key添加到GitHub中,否則進(jìn)入第二步生成SSH key
2. 生成新的ssh key
第一步:生成public/private rsa key pair
在命令行中輸入ssh-keygen -t rsa -C "your_email@example.com"
默認(rèn)會在相應(yīng)路徑下(/your_home_path)生成id_rsa
和id_rsa.pub
兩個文件,如下面代碼所示
gcl:~ smartlei$ ssh-keygen -t rsa -C "http://igit.58corp.com"
Generating public/private rsa key pair.
//說明會在這個路徑下/Users/smartlei/.ssh/id_rsa 生成id_rsa和id_rsa.pub文件,
//如果你敲入別的地址則為在別的地址生生成,例如我在/Users/smartlei/.ssh/id_rsa_igit
//這個文件下生成id_rsa_igit 文件文件名也可以修改()
Enter file in which to save the key (/Users/smartlei/.ssh/id_rsa): /Users/smartlei/.ssh/id_rsa_igit
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/smartlei/.ssh/id_rsa_igit.
Your public key has been saved in /Users/smartlei/.ssh/id_rsa_igit.pub.
The key fingerprint is:
SHA256:++Ik2wTYxuEz5UP/G+XEo7ju8pM8SZhol0ifwdZa15U http://igit.58corp.com
The key's randomart image is:
+---[RSA 2048]----+
| .|
| E.|
| ..o. . . |
| =.=+.o ... |
| ..O=SO.. = |
| .++Oo.o = . |
| ...+o.o+ . |
| *o.*. o |
| ..o**o. |
+----[SHA256]-----+
"your_email@example.com" 郵箱干嘛用的
每次生成密鑰,看到國內(nèi)的博客,都要求輸入郵箱。但不知道意義何在。
后來在stackOverFlow上看到這個答案。
The email is only optional field to identify the key.
郵箱僅僅是識別用的key
When you create the ssh you type (for example):
ssh-keygen -t rsa -C “any comment can be here”
當(dāng)你創(chuàng)建ssh的時候
-t = The type of the key to generate
密鑰的類型
-C = comment to identify the key
用于識別這個密鑰的注釋
So the Comment is for you only and you can put anything inside.
Many sites and software are using this comment as the key name.
所以這個注釋你可以輸入任何內(nèi)容,很多網(wǎng)站和軟件用這個注釋作為密鑰的名字
第二步:輸入passphrase(密碼:某些網(wǎng)站clone時需要密碼)(本步驟可以跳過)
設(shè)置passphrase后,進(jìn)行版本控制時,每次與GitHub通信都會要求輸入passphrase,以避免某些“失誤”
sample result:
第三步:將新生成的key添加到ssh-agent中:
ssh-add ~/.ssh/id_rsa
Mac 系統(tǒng)內(nèi)置了一個 Keychain 的服務(wù)及其管理程序,可以方便的幫你管理各種秘鑰,其中包括 ssh 秘鑰。
ssh-add 默認(rèn)將制定的秘鑰添加在當(dāng)前運行的 ssh-agent 服務(wù)中,但是你可以改變這個默認(rèn)行為讓它添加到 keychain 服務(wù)中,讓 Mac 來幫你記住、管理并保障這些秘鑰的安全性。
你所要做的就是執(zhí)行下面的命令:
$ ssh-add -K [path/to/your/ssh-key]
之后,其他的程序請求 ssh 秘鑰的時候,會通過 Keychain 服務(wù)來請求。
3. 將ssh key添加到GitHub中
用自己喜歡的文本編輯器打開id_rsa.pub
文件,里面的信息即為SSH key,將這些信息復(fù)制到GitHub的Add SSH key
頁面即可
不同的操作系統(tǒng),均有一些命令,直接將SSH key從文件拷貝到粘貼板中,如下:
mac
windows
linux