Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use multiple id_rsa files (SSH-KEYGEN) to push on github

I am using the following command to generate SSH-Keygen on my MAC

ssh-keygen -t rsa -b 4096 -C "<myemail to github>"

I want to create two SSH-keygen for my two GitHub accounts and then use them separately pushing to individual GitHub account. But when I create SSH-keygen file by default id_rsa file is used to login which allows only one git account to connect.

Please help me that how I can provide the correct SSH-keygen file while pushing the code to the GitHub repository.

like image 573
Nitesh Malviya Avatar asked Sep 16 '25 07:09

Nitesh Malviya


1 Answers

Let's assume your home directory is /home/userName and your ssh keys are stored in the .ssh subdirectory (the default location on Linux). First, generate SSH keys with different names:

ssh-keygen -t rsa -b 4096 -f /home/userName/.ssh/id_rsa_1
ssh-keygen -t rsa -b 4096 -f /home/userName/.ssh/id_rsa_2

That will create the following key files:

/home/userName/.ssh/id_rsa_1
/home/userName/.ssh/id_rsa_1.pub
/home/userName/.ssh/id_rsa_2
/home/userName/.ssh/id_rsa_2.pub

Let's also assume that id_rsa_1 is intended for use with a GitHub account called user_1, and that id_rsa_2 will be used for user_2.

Steps:

  1. Copy the contents of the .pub files to the respective accounts in GitHub:
    Settings -> SSH Keys -> New SSH Key -> paste key in the text box
  2. Edit (or create if it doesn't exist) the file /home/userName/.ssh/config. We're going to assign separate aliases for each GitHub account, and map them to github.com. We'll call the aliases host_1 and host_2. The config file should look like this:
Host host_1.github.com
    HostName github.com
    User git
    Port 22
    IdentityFile /home/userName/.ssh/id_rsa_1
Host host_2.github.com
    HostName github.com
    User git
    Port 22
    IdentityFile /home/userName/.ssh/id_rsa_2
  1. Now we can clone the repositories using the aliases assigned in the config file. If there is a repo called repo_1 under account user_1, it can be cloned using this command:
git clone git@host_1.github.com:user_1/repo_1

Similarly, for repo_2 under user_2:

git clone git@host_2.github.com:user_2/repo_2

Hopefully it's clear what is happening: running git commands on a remote host_N.github.com with the ssh syntax tells git to use SSH as its transport. When SSH finds the DNS name for the remote in the config file, it discovers that it should actually connect to github.com and to use the key /home/userName/.ssh/id_rsa_N to authenticate.

like image 81
Z4-tier Avatar answered Sep 19 '25 01:09

Z4-tier