Configure SSH access for two GitHub accounts on your local machine

日月星辰 发布在Tools

Step 1: Generate SSH Keys

  1. Open your terminal.

  2. Generate a new SSH key for each GitHub account. Replace youremail@example.com with your email associated with each GitHub account.

    For the first account:

    ssh-keygen -t rsa -b 4096 -C "youremail1@example.com"

    When prompted to save the key, give it a unique name (e.g., id_rsa_github_personal):

    Enter file in which to save the key (/home/you/.ssh/id_rsa): /home/you/.ssh/id_rsa_github_personal
    

    For the second account:

    ssh-keygen -t rsa -b 4096 -C "youremail2@example.com"

    Save this key with another unique name (e.g., id_rsa_github_work):

    Enter file in which to save the key (/home/you/.ssh/id_rsa): /home/you/.ssh/id_rsa_github_work
    

Step 2: Add SSH Keys to the SSH Agent

  1. Start the SSH agent:

    eval "$(ssh-agent -s)"
  2. Add your SSH keys:

    ssh-add ~/.ssh/id_rsa_github_personal
    ssh-add ~/.ssh/id_rsa_github_work

Step 3: Add SSH Keys to Your GitHub Accounts

  1. Copy the SSH key to your clipboard:

    cat ~/.ssh/id_rsa_github_personal.pub

    Go to GitHub (for the first account) > Settings > SSH and GPG keys > New SSH key. Paste the key and save.

  2. Repeat the process for the second account:

    cat ~/.ssh/id_rsa_github_work.pub

    Add this key to the second GitHub account in the same way.

Step 4: Configure SSH Config File

  1. Open (or create) the SSH config file:

    nano ~/.ssh/config
  2. Add configurations for both accounts:

    # Personal account
    Host github.com-personal
        HostName github.com
        User git
        IdentityFile ~/.ssh/id_rsa_github_personal
    
    # Work account
    Host github.com-work
        HostName github.com
        User git
        IdentityFile ~/.ssh/id_rsa_github_work
    

Step 5: Clone Repositories Using the Correct Host

When cloning repositories, use the corresponding host defined in your SSH config:

For the personal account:

git clone git@github.com-personal:username/repo.git

For the work account:

git clone git@github.com-work:username/repo.git

Conclusion

You should now be able to manage two GitHub accounts using SSH without any issues! Each account will use the appropriate SSH key when you clone or push to repositories.