Search code examples
githubsshconfig

Pushing Code to Repositories Under Multiple GitHub Accounts with SSH Configuration Issue


I am facing issues while attempting to push code to repositories hosted under two different GitHub accounts, namely James and John. Initially, I was working only with repositories under the James account, and now I am trying to add the John account as well. Despite following the steps below to configure SSH keys for both accounts, I am encountering an error.

Here are the steps I took:

  1. Created a private/public key pair for the James account using the command:

    ssh-keygen -t ed25519 -C "jamesemailaddress@example.com" -f james_key

Added the key to the SSH agent using:

   ssh-add ~/.ssh/james_key
  1. Repeated the same process for the John account:

    ssh-keygen -t ed25519 -C "johnsemailaddress@example.com" -f johns_key

Added the key to the SSH agent:

 ssh-add ~/.ssh/johns_key
  1. Configured the SSH config file at ~/.ssh/config as follows:

    # James GitHub account
    Host github.com-james
        HostName github.com
        User git
        IdentityFile ~/.ssh/james_key
    
    # Johns GitHub account
    Host github.com-john
        HostName github.com
        User git
        IdentityFile ~/.ssh/johns_key
    
  2. Copied the respective public keys for both James and John to the GitHub SSH Keys and GPG Keys sections successfully.

However, when attempting to push code to a repository under John's account, I encounter the following error message:

ERROR: Repository not found. fatal: Could not read from remote repository.

Please make sure you have the correct access rights

Additionally, when running the command ssh -T git@github.com within John's repository, the message indicates that James was successfully authenticated. This suggests that despite the configuration, the SSH client is recognizing only the settings for James and not for John.

Could someone please guide me on how to rectify this issue? Your assistance is much appreciated.


Solution

  • Your ssh config settings are only used when you specify github.com-james or github.com-john as the host names.

    Testing with

    ssh -T github.com-james
    

    should work (no need to specify the git username again either)

    In order for this to be used with git, you need to make sure the remote uses this host as well, as in your git configuration should read

    [remote "origin"]
        url = github.com-james:some/repo.git
        fetch = ...
    

    (or check with git remote -v)

    Assuming "origin" branch you can achieve this with the command

    cd james_cloned_repo/
    git remote set-url origin github.com-james:some/repo.git