postsgit-config-multi-ssh-key

Git配置多个SSH-Key

Abstract

我们在日常工作中会遇到公司有个gitlab,还有些自己的一些项目放在github上。这样就导致我们要配置不同的 SSH KEY 对应不同的环境。下面我们来看看具体的操作.

我们在日常工作中会遇到公司有个 gitlab,还有些自己的一些项目放在 github 上。 这样就导致我们要配置不同的 SSH KEY 对应不同的环境。下面我们来看看具体的操作.

生成一个公司用的 SSH-Key

ssh-keygen -t rsa -C 'youremail@yourcompany.com' -f ~/.ssh/id-rsa

~/.ssh/目录会生成 id-rsaid-rsa.pub 私钥和公钥。 我们将 id-rsa.pub 中的内容粘贴到公司 github 服务器的 SSH-Key 的配置中。

生成一个 github 用的 SSH-Key

ssh-keygen -t rsa -C "youremail@your.com” -f ~/.ssh/github-rsa

~/.ssh/目录会生成 github-rsagithub-rsa.pub 私钥和公钥。 我们将 github-rsa.pub 中的内容粘贴到公司 github 服务器的 SSH-Key 的配置中。

添加私钥

ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/github_rsa

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

ssh-agent bash

然后再运行 ssh-add 命令。可以通过 ssh-add -l 来确私钥列表, 可以通过 ssh-add -D 来清空私钥列表

ssh-add 这个命令不是用来永久性的记住你所使用的私钥的。实际上,它的作用只是把你指定的私钥添加到 ssh-agent 所管理的一个 session 当中。而 ssh-agent 是一个用于存储私钥的临时性的 session 服务,也就是说当你重启之后,ssh-agent 服务也就重置了。

如果是为了永久记住对应的私钥是哪个,我们不能依赖 ssh-agent 服务。能依赖什么则取决于以下哪些方案适合你的使用场景, 下面提供了两种方式:

基于 Mac OSX 的 Keychain 服务,通过 ssh-add -K 直接添加到 keychains 中。

ssh-add -K ~/.ssh/id_rsa
ssh-add -K ~/.ssh/github_rsa

直接添加 ssh config 文件,这就是接下来要讲的。

修改配置文件

~/.ssh 目录下新建一个 config 文件

touch config

添加内容:

# gitlab
Host gitlab.com
HostName gitlab.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_rsa

目录结构

cd 进入 ~/.ssh 目录结构如下:

    .
    ├── config
    ├── id_rsa
    ├── id_rsa.pub
    ├── id_rsa_ghub
    ├── id_rsa_ghub.pub
    └── known_hosts

测试

打开终端输入:

ssh -T git@github.com

输出:

Hi yugasun! You've successfully authenticated, but GitHub does not provide shell access.

就表示成功的链接上 github 了, 也可以试试链接公司的 gitlab.

相关文章

Continue your reading

When you finish this article, use these paths to continue the thread.

cd ../posts

// tags

Explore adjacent topics and move sideways through the knowledge graph.

// continue reading