生成多個git ssh密鑰

若是你已經有了一套名爲 id_rsa 的公祕鑰,將要生成另一個公鑰,好比 aysee ,你也可使用任何你喜歡的名字。javascript

步驟以下:java

 

一、生成一個新的自定義名稱的公鑰:git

ssh-keygen -t rsa -C "YOUR_EMAIL@YOUREMAIL.COM" -f ~/.ssh/aysee

  執行命令後,生成命名的公鑰和生成默認公鑰的步驟同樣。github

執行完成後,會在 ~/.ssh/目錄下生成一個 aysee 和 aysee.pub 文件。shell

二、在 SSH 用戶配置文件 ~/.ssh/config 中指定對應服務所使用的公祕鑰名稱,若是沒有 config 文件的話就新建一個,並輸入如下內容:bash

Host github.com www.github.com
  IdentityFile ~/.ssh/aysee

三、添加 aysee.pub 到你的git服務器網站上。服務器

四、測試配置文件是否正常工做ssh

ssh -T git@gitcafe.com

  若是,正常的話,會出現以下提示:ide

Hi USERNAME! You've successfully authenticated, but github does not provide shell access.

  若是出現以下提示,則說明有權限問題測試

Permission denied (publickey)

  若是有權限問題的狀況下,你對項目執行push操做的時候,會獲得以下提示:

Warning: Permanently added the RSA host key for IP address '192.30.252.129' to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

  

多用戶時出現權限問題的緣由:

github使用SSH與客戶端鏈接。若是是單用戶(first),生成密鑰對後,將公鑰保存至 GitHub ,每次鏈接時SSH客戶端發送本地私鑰(默認~/.ssh/id_rsa)到服務端驗證。單用戶狀況下,鏈接的服務器上保存的公鑰和發送的私鑰天然是配對的。可是若是是 多用戶 (first,second),咱們在鏈接到second的賬號時,second保存的是本身的公鑰,可是SSH客戶端依然發送默認私鑰,即first的私鑰,那麼這個驗證天然沒法經過。

 

解決ssh權限問題():

一般一臺電腦生成一個ssh不會有這個問題,當一臺電腦生成多個ssh的時候,就可能遇到這個問題,解決步驟以下:

一、查看系統ssh-key代理,執行以下命令

$ ssh-add -l

  以上命令若是輸出  The agent has no identities. 則表示沒有代理。若是系統有代理,能夠執行下面的命令清除代理:

$ ssh-add -D

二、而後依次將不一樣的ssh添加代理,執行命令以下:

$ ssh-add ~/.ssh/id_rsa
$ ssh-add ~/.ssh/aysee

 你會分別獲得以下提示:

2048 8e:71:ad:88:78:80:b2:d9:e1:2d:1d:e4:be:6b:db:8e /Users/aysee/.ssh/id_rsa (RSA)

  和

2048 8e:71:ad:88:78:80:b2:d9:e1:2d:1d:e4:be:6b:db:8e /Users/aysee/.ssh/id_rsa (RSA)
2048 a7:f4:0d:f1:b1:76:0b:bf:ed:9f:53:8c:3f:4c:f4:d6 /Users/aysee/.ssh/aysee (RSA)

  若是使用 ssh-add ~/.ssh/id_rsa的時候報以下錯誤,則須要先運行一下 ssh-agent bash 命令後再執行 ssh-add ...等命令

Could not open a connection to your authentication agent.

  

三、配置 ~/.ssh/config 文件

  若是沒有就在~/.ssh目錄建立config文件,該文件用於配置私鑰對應的服務器

# Default github user(first@mail.com)

Host github.com
HostName github.com
User git
IdentityFile C:/Users/username/.ssh/id_rsa

# aysee (company_email@mail.com) Host github-aysee HostName github.com User git IdentityFile C:/Users/username/.ssh/aysee

  Host隨意便可,方便本身記憶,後續在添加remote是還須要用到。 配置完成後,在鏈接非默認賬號的github倉庫時,遠程庫的地址要對應地作一些修改,好比如今添加second賬號下的一個倉庫test,則須要這樣添加:

git remote add test git@github-aysee:ay-seeing/test.git 
#並不是原來的git@github.com:ay-seeing/test.git

  ay-seeing 是github的用戶名

 

四、測試 ssh

ssh -T git@github.com

  你會獲得以下提示,表示這個ssh公鑰已經得到了權限

Hi USERNAME! You've successfully authenticated, but github does not provide shell access.
相關文章
相關標籤/搜索