ITeye博客

(转)配置多个git远程仓库的ssh-Key切换

chiyx · 2013-05-20 23:28 · 开发工具 · 开源软件 · Git · 版本控制 · Markdown

转载地址:http://omiga.org/blog/archives/2269

 

目前的git仓库如github都是通过使用SSH与客户端连接,如果只是固定使用单个git仓库的单个用户

(first),生成生成密钥对后,将公钥保存至github,每次连接时SSH客户端发送本地私钥(默认~/.ssh/id_rsa)到服务端验证。单用户情况下,连接的服务器上保存的公钥和发送的私钥自然是配对的。

但是在实际工作中,一般公司内部都有自己的独立的git仓库(gitlab.xxx.com),于是就会存在这样的情

况,在github有私人的账号first,公司的gitlab中的工作账号sencord,first和second因为环境不同,必须配置不同的username和email。所以必须对每个账号分别生成独立的公钥密钥对。在链接到github时,使用first的公钥密钥对,链接到公司内的gitlab时,使用second的公钥密钥对。假设first的密钥文件为id_rsa,second的密钥文件为id_rsa_second.

在默认情况下,ssh总是使用id_rsa密钥文件进行链接,这样对于second账号的认证自然是不通过的,

不过,要实现多帐号下的SSH key切换在客户端做一些配置即可。

首先cd到~/.ssh 使用 ssh-keygen -t -rsa -C ‘second@mail.com’(为你工作账号的邮箱地址) 生成新的

SSH key:id_rsa_second

ssh-keygen -t rsa -C 'second@mail.com' -f id_rsa_second

生成后将新的ssh public key添加到内部的gitlab仓库中, 然后在~/.ssh 目录下创建config文件,该文件用于配置私钥对应的服务器。内容如下:

Host gitlab.xxx.com ##可以随意命名,链接时使用这个名字
    HostName gitlab.xxx.com
    User git
    Port 22
    IdentityFile ~/.ssh/id_rsa_second

 执行

git clone git@gitlab.xxx.com:second/test.git

 时会使用second的id_rsa_second与服务器进行连接.而链接非gitlab.xxx.com服务器时则会使用first的密钥进行链接。至此,大功告成!

 

**注意:**git根据配置文件的user.email来获取git帐号显示author信息,所以对于多帐号用户一定要

记得将user.email改为相应的email(second@mail.com)。

评论(4)

  1. #4 楼 · wushexin · 2015-08-06 16:38

    Bad owner or permissions on $HOME/.ssh/config The ssh with RHEL 4 is a lot more anal about security checking. In my case, it was the fact that $HOME/.ssh/config was group-writable which was causing it to barf. To fix:

    $ cd ~/.ssh $ chmod 600 * Note that this error message is kind of stupid, since $HOME/.ssh had permissions 700 on it, and $HOME had 750 permissions on it. If any process managed to evade those permissions, changing the permissions on the config file would be similarly defeated.

  2. #3 楼 · chiyx · 2014-04-23 23:56

    十井_ writes:

    都是程序员 整篇文章都copy了 为什么就不能多加个转呢? :?:

    这篇文章当时是刚好是为了方便自己下次设置的时候不用到处找而记录的,忘记附上转载额, :oops:

  3. #2 楼 · 十井_ · 2014-04-22 17:40

    http://omiga.org/blog/archives/2269

  4. #1 楼 · 十井_ · 2014-04-22 17:40

    都是程序员 整篇文章都copy了 为什么就不能多加个转呢? :?:

评论功能维护中,当前仅展示历史评论。