github 多用户多ssh密钥对环境配置

问题

  • github有多个账号,不同账号需要对应不同的repository,不能混淆

环境

2个github账号,分别是

  • myself_account
  • mycompany_account

配置

  • 首先为2个账号分别生成密钥对
ssh-keygen -t rsa -C 'myself_account@A.com' -f ~/.ssh/id_rsa_myself
ssh-keygen -t rsa -C 'mycompany_account@B.com' -f ~/.ssh/id_rsa_mycompany
  • 将2个公钥id_rsa_myself.pub和id_rsa_mycompany.pub分别配置到github
  • 修改ssh配置文件 ~/.ssh/config
Host github.com
        HostName github.com
        IdentityFile ~/.ssh/id_rsa_myself
        IdentitiesOnly yes

Host github-mycompany
        HostName github.com
        IdentityFile ~/.ssh/id_rsa_mycompany
        IdentitiesOnly yes
  • 将公钥配置到Git服务器
  • 将密钥对加入ssh-agent
ssh-agent bash
ssh-add ~/.ssh/id_rsa_myself
ssh-add ~/.ssh/id_rsa_mycompany

验证

ssh -T git@github.com
ssh -T git@github-mycompany

可以连接的话,会返回消息
Hi XXX! You've successfully authenticated, but GitHub does not provide shell access.

使用

之后myself_account使用的时候,因为Host配置的github.com,可以正常使用,而mycompany_account账号clone的时候,要将github.com替换为github-mycompany

git clone git@github-mycompany:XXX/YYY.git

clone后注意配置下用户邮箱和名字就可以了

参考

原文地址:https://www.cnblogs.com/wendelhuang/p/15122016.html