SSH Keys with Multiple GitHub Accounts

Motivation

Allows multiple SSH keys to support multiple Github account such that pushing and pulling changes from and to the corresponding GitHub account can be done automatically and smoothly without having to specify the specific account info manually.

Assumptions

  1. For simplicity, only two accounts correspond to Github accounts, respectively.
  • personal: account name personal Github account
  • company: account name for a company Github account

Create keys with ssh commands

Follow the steps listed in the article https://medium.com/@trionkidnapper/ssh-keys-with-multiple-github-accounts-c67db56f191e

Create keys with SourceTree

  1. Log into personal account from the web browser
  2. [SourceTree] -> [Preferences] -> [Account] -> [Add]
  3. Add the personal account and connect to Github
  4. [Generate key] for personal account
  5. Create new SSH key from [New SSH Key] in the [Settings] -> [SSH and GPG keys] section
  6. Copy and paste the generated public key in the newly created key section
  7. Add the private key to ssh-agent

ssh-add ~/.ssh/id_rsa_personal

Output of vim ~/.ssh/config looks like this:

# --- Sourcetree Generated ---
Host github.com
        HostName github.com
        User personal
        PreferredAuthentications publickey
        IdentityFile /Users/neil/.ssh/personal-GitHub
        UseKeychain yes
        AddKeysToAgent yes
  1. Repeat step 1-7 to create and config SSH key for the company account.
    Output of vim ~/.ssh/config looks like this:
# --- Sourcetree Generated ---
Host github.com
        HostName github.com
        User personal
        PreferredAuthentications publickey
        IdentityFile /Users/neil/.ssh/personal-GitHub
        UseKeychain yes
        AddKeysToAgent yes

# --- Sourcetree Generated ---
Host company-Github
        HostName github.com
        User company
        PreferredAuthentications publickey
        IdentityFile /Users/neil/.ssh/personal-GitHub
        UseKeychain yes
        AddKeysToAgent yes
  1. Replace company-Github with company.githhub.com to avoid authenticating company repository with personal account. This is a VERY imporat step, failing to do so will result in error like
ERROR: Permission to company/cloudme.git denied to personal.
fatal: Could not read from remote repository.

It's a known SourceTree issue.

  1. clone/pull/push repo
    Clone new repos

git clone git@github.com:personal/cloudme.git
git clone git@company.github.com:company/cloudme.git

pull/push exiting repo, change
from

[remote "origin"]
        url = git@github.com:company/cloudme.git

to

[remote "origin"]
        url = git@company.github.com:company/cloudme.git
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。