最近和同學(xué)在合作開發(fā)一個項目啸蜜,就需要協(xié)作開發(fā)杯聚,需要把代碼放到github上烛芬。又不想放到自己的私人github賬號,就干脆新注冊了一個新的github賬號宜咒。
要想給github賬號中的項目提交代碼惠赫,就需要把電腦上SSH key
的公鑰添加到對應(yīng)github賬號中去,才有權(quán)限提交代碼荧呐。首先想到的就把電腦上現(xiàn)有的SSH key
的公鑰添加到github中,出現(xiàn)出乎意料的提示Key is already in use
纸镊。
說我的密鑰已經(jīng)被使用倍阐,那我就新生成一對密鑰咯。打開終端逗威,輸入下面命令峰搪。
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
提示Enter file in which to save the key (/Users/nchkdxlq/.ssh/id_rsa):
,如果直接按回車凯旭,會生成以id_rsa
開頭命名的密鑰對概耻,會覆蓋原來在.ssh
目錄下面已有的id_rsa
密鑰。所以需要輸入生成密鑰的名稱singsender_rsa
罐呼,按回車之后就會在.ssh
目錄下生成singsender_rsa
私鑰和singsender_rsa.pub
公鑰鞠柄。
把singsender_rsa.pub
公鑰添加到github賬號中,沒有提示密鑰已使用嫉柴,說明密鑰添加成功了厌杜。
這時開心的在終端執(zhí)行push
命令,發(fā)現(xiàn)并沒有把代碼push
到github上计螺,并且給了我如下的提示夯尽。
ERROR: Permission to singsengder/test.git denied to nchkdxlq.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
為什么會出現(xiàn)這樣的提示呢?原因是這樣的登馒,在每次push
的時候匙握,本地的私鑰都會和服務(wù)端(github
)的公鑰去匹配,如果匹配成功就可以push
了陈轿;而在默認(rèn)情況下圈纺,本地的私鑰都會讀取id_rsa
文件,而賬號中對應(yīng)的公鑰singsender_rsa.pub
麦射,所以當(dāng)然會報沒有權(quán)限的錯誤赠堵。
那怎樣讓不同的github
賬號對應(yīng)不同的密鑰對呢?需要做兩個設(shè)置
新建config文件
在~/.ssh
目錄下新建config
文件并添加如下內(nèi)容法褥,該文件用于設(shè)置私鑰對應(yīng)的服務(wù)器茫叭。
#Default Account
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
#singsender singsender_github.com為服務(wù)器的別名
Host singsender_github.com
HostName github.com
User git
IdentityFile ~/.ssh/singsender_rsa
修改具體項目的config文件
在.git/config
文件中,有一行設(shè)置url
的配置半等。
默認(rèn)配置
url = git@github.com:singsengder/test.git
修改后
url = singsender_github.com:singsengder/test.git
修改url
配置還有更簡單的方式揍愁,在對應(yīng)的項目中執(zhí)行命令
git remote set-url origin singsender_github.com:singsengder/test.git
驗證授權(quán)
$ ssh -T singsender_github.com
Hi singsengder! You've successfully authenticated, but GitHub does not provide shell access.
授權(quán)成功呐萨,可以往新賬號的github賬號提交代碼了。