github/gitlab 管理多個ssh key

以前只使用一個 ssh key 在github上提交代碼,由於工作原因,需要再添加一個ssh key在公司的 gitlab上提交代碼,下面記錄下配置過程,防止遺忘。
說明下我的環境是 Win7 + msysgit + GitBash, 相信 *nux + bash 也是同樣的道理。

生成並添加第一個ssh key

第一次使用ssh生成key,默認會在用戶~(根目錄)下生成 id_rsa, id_rsa.pub 2個文件;所以需要添加多個ssh key時也會生成對應的私鑰和公鑰。

$ ssh-keygen -t rsa -C "[email protected]"

在Git Bash中執行這條命令一路回車,會在 ~/.ssh/ 目錄下生成 id_rsa 和 id_rsa.pub 兩個文件,用文本編輯器將 id_rsa_pub 中的內容複製一下粘貼到github(gitlab)上。

生成並添加第二個ssh key

$ ssh-keygen -t rsa -C "[email protected]"

注意不要一路回車,要給這個文件起一個名字, 比如叫 id_rsa_github, 所以相應的也會生成一個 id_rsa_github.pub 文件。

091222268402433

目錄結構如下:
091222046992263

添加私鑰

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

如果執行ssh-add時提示"Could not open a connection to your authentication agent",可以現執行命令:

$ ssh-agent bash

然後再運行ssh-add命令。

# 可以通過 ssh-add -l 來確私鑰列表$ ssh-add -l# 可以通過 ssh-add -D 來清空私鑰列表$ ssh-add -D

修改配置文件

在 ~/.ssh 目錄下新建一個config文件

touch config

添加內容:

# gitlabHost gitlab.com
    HostName gitlab.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa# githubHost github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_github

測試

$ ssh -T [email protected]

輸出
Hi user! You've successfully authenticated, but GitHub does not provide shell access. 就表示成功的連上github了


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章