單用戶情況:
ssh-add id_rsa
如果出現Could not open a connection to your authentication agent的錯誤,就試着先用以下命令:
ssh-agent bash ssh-add id_rsa
添加完之后 登陸Github 點擊 網頁右上側的 Account Setting 按鈕 - 選擇 ssh-keys 點擊Add SSH Key ,在title中輸入名字,然后將公約即id_rsa.pub添加到ssh-key處。
在git bash的命令行中輸入
ssh -T git@github.com 如果能正常訪問即可
$ ssh -T git@github.com Enter passphrase for key 'C:/Users/kunkun/.ssh/github.rsa': Hi kunkun01! You've successfully authenticated, but GitHub does not provide shel l access.
多賬戶又分為兩種情況
也可以參考老外寫的 Git config for mutiply SSH keys
1、針對同一個服務器的同用戶(比如 我平時開發開源的小東東,有的是一個賬號是公司的賬號對外開源項目用的,另外我自己也比較崇尚開源,所以自己也有了Github賬號)
2,針對不同服務器的用戶(現在pass平台 部署應用都是通過git來管理的,比如常見的Openshift,Heroku appfog等,在這里我也注冊了賬號)
在我們訪問git服務器的時候,如果通過ssh的方式話,訪問不同的服務器要使用不同的ssh-key。經過在第一步的過程中,在創建ssh-key的默認命名為id_rsa,如果使用不同的賬戶的,必須得給不同的key設置不同的名字,否則如果繼續使用默認名字的話,會把之前的id_rsa覆蓋掉。
具體操作如下 user2是我的另外一個Github賬戶
1、新建user2的SSH Key
#新建SSH key: $ cd ~/.ssh # 切換到C:\Users\Administrator\.ssh ssh-keygen -t rsa -C "mywork@email.com" # 新建工作的SSH key # 設置名稱為id_rsa_work Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa): id_rsa_work
2、新密鑰添加到SSH agent中
因為默認只讀取id_rsa,為了讓SSH識別新的私鑰,需將其添加到SSH agent中:
ssh-add ~/.ssh/id_rsa_work
如果出現Could not open a connection to your authentication agent的錯誤,就試着用以下命令:
ssh-agent bash
ssh-add ~/.ssh/id_rsa_work
(第二步 好像沒什么作用)
3、修改config文件 將賬戶以及git服務器與對應的密鑰關聯。在~/.ssh目錄下找到config文件,如果沒有就創建:
touch config
然后修改如下: 我的config配置如下:
# 該文件用於配置私鑰對應的服務器 # Default github user(first@mail.com) Host github.com HostName github.com User git IdentityFile C:/Users/Administrator/.ssh/id_rsa # second user(second@mail.com) # 建一個github別名,新建的帳號使用這個別名做克隆和更新 Host github2 HostName github.com User git IdentityFile C:/Users/Administrator/.ssh/id_rsa_work
其規則就是:從上至下讀取config的內容,在每個Host下尋找對應的私鑰。這里將GitHub SSH倉庫地址中的git@github.com替換成新建的Host別名如:github2,那么原地址是:git@github.com:funpeng/Mywork.git,替換后應該是:github2:funpeng/Mywork.git.
4、用記事本打開新生成的~/.ssh/id_rsa2.pub文件,將里面的內容添加到GitHub后台。
可不要忘了添加到你的另一個github帳號下的SSH Key中。
5、測試:
$ ssh -T git@github.com Hi BeginMan! You've successfully authenticated, but GitHub does not provide shel l access.
$ ssh -T github2 Hi kunkun01! You've successfully authenticated, but GitHub does not provide shell access.
6、應用
測試成功,那么我嘗試在我的work目錄下克隆我@126.com賬號下的遠程倉庫。如下:
$ git clone github2:kunkun01/Mywork.git Cloning into 'Mywork'... remote: Counting objects: 3, done. remote: Total 3 (delta 0), reused 0 (delta 0) Receiving objects: 100% (3/3), done. Checking connectivity... done
如果你只是通過這篇文章中所述配置了Host,那么你多個賬號下面的提交用戶會是一個人,所以需要通過命令git config --global --unset user.email
刪除用戶賬戶設置,在每一個repo下面使用git config --local user.email '你的github郵箱@mail.com'
命令單獨設置用戶賬戶信息