◎ 通過 SSH 克隆倉庫
我們克隆 GitHub 上的倉庫時,一般是通過默認的 HTTPS 的方式,而非上面這種 SSH 的方式。
對於克隆倉庫的話,我們使用起來是感受不到這兩種方式的差別的。但是,當我們要將本地的改動提交到 GitHub 的時候,使用 SSH 就會比使用 HTTPS 方便很多——我們無需每次輸入用戶名和密碼。
單帳號
$ ssh-keygen -t rsa -b 4096 -C "[email protected]"
怎樣使用 SSH 呢?首先,你需要通過以上命令生成 SSH 密鑰對。當然,將上面的郵箱地址改爲你自己在 GitHub 上的郵箱地址。然後,如果你是第一次生成的話,一路回車即可(口令 passphrase 非必須)。
之後,cat ~/.ssh/id_rsa.pub
查看生成的公鑰並複製,再去 GitHub 上設置一個 New SSH key,標題隨便起一個(比如:我的電腦),然後粘貼公鑰即可。
最後,如果你 git clone
或 git remote add
的是 HTTPS 的地址[1],那麼要修改倉庫的遠程倉庫鏈接地址爲 SSH 地址,比如:
git remote set-url origin [email protected]:reuixiy/hugo-theme-meme.git
此外,當你本地第一次連接 GitHub 的服務器時,可能會有警告信息,輸入 yes
回車即可。
多帳號
# 帳號一 $ ssh-keygen -t rsa -b 4096 -C "[email protected]" Generating public/private rsa key pair. Enter file in which to save the key (/home/archie/.ssh/id_rsa): /home/archie/.ssh/id_rsa_reuixiy # 帳號二 $ ssh-keygen -t rsa -b 4096 -C "[email protected]" Generating public/private rsa key pair. Enter file in which to save the key (/home/archie/.ssh/id_rsa): /home/archie/.ssh/id_rsa_yixiuer
⚠️ 特別注意一下,這裏你可不要直接默認回車了,當你看到以下提示時:
Enter file in which to save the key (/home/archie/.ssh/id_rsa):
注意修改一下默認的 id_rsa
,建議在後面加上你的 GitHub 用戶名,比如修改爲 id_rsa_reuixiy
,見我上面的操作。
然後,我們要將生成的兩個密鑰添加到 ssh-agent:
$ eval "$(ssh-agent -s)" $ ssh-add ~/.ssh/id_rsa_reuixiy $ ssh-add ~/.ssh/id_rsa_yixiuer
接下來,添加一個 config
文件配置下 SSH:
$ vim ~/.ssh/config
輸入以下內容(自行修改 host
和 IdentityFile
):
host reuixiy.github.com Hostname github.com User git IdentityFile ~/.ssh/id_rsa_reuixiy host yixiuer.github.com Hostname github.com User git IdentityFile ~/.ssh/id_rsa_yixiuer
類似,修改下相應倉庫的遠程倉庫鏈接地址,比如:
# 帳號一 ~/hugo-theme-meme $ git remote set-url origin [email protected]:reuixiy/hugo-theme-meme.git # 帳號二 ~/yixiuer.me $ git remote set-url origin [email protected]:yixiuer/yixiuer.me.git
特別注意:主機名分別是 reuixiy.github.com
和 yixiuer.github.com
,而不再是默認的 github.com
了,以後克隆倉庫時也要注意,修改爲帳號的相應主機名。
最後,將相應的公鑰添加到你的相應 GitHub 帳號,成功!
如果你不記得了,可以查看一下倉庫下的 .git
文件夾下的 config
文件確認一下。
參考