git生成ssh key和多賬號支援

看風景就發表於2016-04-15

git配置ssh

1.首先設定git的全域性user name和email

$ git config --global user.name "ygtzz"
$ git config --global user.email "ygtzz@123.com"

2.進入.ssh目錄(沒有就新建一個)

Windows cd C:/Users/userName/.ssh
Mac cd ~/.ssh

3.終端中執行ssh-keygen生成key

$ ssh-keygen -t rsa -C “ygtzz@123.com”
(在windows上執行時候,要在git bash中執行ssh-keygen,在cmd中可能無法執行,
遇到ssh-keygen不是內部或外部命令,則要在**/Git/usr/bin目錄下找到ssh-keygen.exe,
將**/Git/usr/bin路徑新增到環境變數中)
按3個回車,密碼為空

Your identification has been saved in /home/tekkub/.ssh/id_rsa.
Your public key has been saved in /home/tekkub/.ssh/id_rsa.pub.
The key fingerprint is:
………………

得到兩個檔案
私鑰: id_rsa
公鑰:id_rsa.pub

4.在github或gitlab上新增公鑰

新增多個git賬號支援(例如同時使用github和gitlab)

1.生成新的ssh key
進入.ssh目錄,通過命令ssh-keygen生成ssh key,
在執行命令後,不要回車,第一步要確認key的檔名,可以輸入一個與之前不同的名字
例如 id_rsa_github,其後兩步,皆回車,則會生成兩個檔案

私鑰:id_rsa_github
公鑰: id_rsa_github.pub

將公鑰新增到github上

2.在.ssh下新建config檔案,在其中新增配置

# gitlab
Host gitlab
HostName gitlab.com
User ygtzz

IdentityFile ~/.ssh/id_rsa  //windows: IdentityFile C:\Users\xxx\.ssh\id_rsa

# github
Host github
HostName github.com
User ygtzz
IdentityFile ~/.ssh/id_rsa_github //windows: IdentityFile C:\Users\xxx\.ssh\id_rsa_github

注意:此處Host是HostName的別名,在git clone 地址的時候會使用host的來判別key,進行下載。例如:git@github.com/ygtzz/lazyload.git專案,在配置下,必須使用

git@{Host}/ygtzz/lazyload.git(即git@github/ygtzz/lazyload.git)地址去下載,git才能根據config找到對應的rsa檔案。因此,建議Host和HostName保持一致,這樣clone

時候就不用修改下載地址,直接可以下載。下面是一個支援github,gitlab,碼雲三個git端的配置檔案(已驗證可用):

#gitee
Host git.oschina.net
HostName git.oschina.net
User ygtzz
IdentityFile ~/.ssh/id_rsa_gitee

#gitlab
Host git.xxx.com
Hostname git.xxx.com
User mengweif
IdentityFile ~/.ssh/id_rsa_gitlab

#github
Host github.com
HostName github.com
User ygtzz
IdentityFile ~/.ssh/id_rsa

3.執行ssh-agent讓ssh識別新的私鑰

ssh-add ~/.ssh/id_rsa_new

該命令如果報錯:Could not open a connection to your authentication agent.無法連線到ssh agent,則可執行ssh-agent bash命令後再執行ssh-add命令:

ssh-agent bash
ssh-add ~/.ssh/id_rsa_new

以後,在clone或者add remote的時候,需要把config檔案中的host代替git@remoteaddress中的remoteaddress。

4.在git的工作目錄中,設定本地的使用者名稱和郵箱

$ git config --local user.name "github使用者名稱"
$ git config --local user.email "註冊郵箱"

如果不設定使用者名稱,則能正常提交,但提交的使用者名稱會是global設定的使用者名稱


參考:https://my.oschina.net/csensix/blog/184434

         https://www.jianshu.com/p/89cb26e5c3e8

相關文章