Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aprilmintacpineda/f101bf5fd34f1e6664497cf4b9b9345f to your computer and use it in GitHub Desktop.
Save aprilmintacpineda/f101bf5fd34f1e6664497cf4b9b9345f to your computer and use it in GitHub Desktop.
Beginner Friendly: Using Multiple SSH keys

How to follow this guide

The problem

I have one computer and two different github accounts. One is for work, the other is for my personal stuff. I can't use the same ssh key twice, so I have to use different ssh key for each of my accounts. How do I do that? How do I switch between these ssh keys?

Generate SSH keys

Open your terminal / CMD PROMPT and type the following command:

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

The command will ask ssh to generate a key for you. After running the command, you will see the following feedback:

Generating public/private rsa key pair.

The next line you will see would be:

Enter file in which to save the key (/Users/sprlwrks/.ssh/id_rsa): 

Here, you can specify a directory and filename for the ssh key that will be generated. The default is /Users/sprlwrks/.ssh/id_rsa. It will be saved in /Users/sprlwrks/.ssh/ with the file name id_rsa. It will generate two files. id_rsa and id_rsa.pub. The id_rsa.pub contains your public key which you will use, you can give this to your team leader or to other people that you want. The id_rsa is the private key, don't want to give this key to anyone.

In this case, since we are going to generate two ssh keys, we don't want to keep the default file name, set it to whatever name you want by giving it /Users/sprlwrks/.ssh/file_name. I named mine id_rsa_personal.

The next line you will see would be:

Enter passphrase (empty for no passphrase): 

If you type a passphrase here, you will have to remember that and type the same passphrase again everytime you use this key. I'll leave it up to you to decide. For me, I did not add any passphrase so I simply pressed enter. The next line would ask you to retype the passphrase again, of course if you left it empty then just press enter.

With all that you should have gotten something that looks like this:

aprilmintacpineda-MacBook-Pro:PWA-W88 aprilmintacpineda$ ssh-keygen -t rsa -b 4096 -C "me@example.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/sprlwrks/.ssh/id_rsa): /Users/sprlwrks/.ssh/id_rsa_personal
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/sprlwrks/.ssh/id_rsa_personal.
Your public key has been saved in /Users/sprlwrks/.ssh/id_rsa_personal.pub.
The key fingerprint is:
0b:0a:9f:58:2d:c8:a3:87:f7:44:17:f6:2c:d8:b7:3a me@example.com
The key's randomart image is:
+--[ RSA 4096]----+
|                 |
|                 |
|      o          |
| . . = +         |
|  = = * S        |
| o B = + o       |
|o + =   o        |
| o o  E.         |
|    . ..         |
+-----------------+

That's your first key. Now run cd ~/.ssh and then run ls. ls would list all files in the directory. You should see the keys that have been generated.

id_rsa_personal			id_rsa_personal.pub

Now try to generate another one by following the same procedure again. I named my second key id_rsa_work. Once you're done you should have the following files (respective to the filename you gave it):

id_rsa_personal			id_rsa_personal.pub			id_rsa_work			id_rsa_work.pub

Adding ssh keys to github accounts (or whatever you use)

First, I'll add my id_rsa_personal ssh key.

1

Go to your github account then go to settings -> SSH and GPG keys. Click on New SSH key button.

2

Go to your terminal again and run this command: cat ~/.ssh/<yourfilename>.pub replacing <yourfilename> with whatever file name you gave it, in this case mine is id_rsa_personal.pub.

After running the commands above, you'll see something like this:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCha2J5mW3i3BgtZ25/FOsxywpLVkx1RgmZunIACBxV5V1lUm9I6J8uP8sP4xst/WwTWzjUY8svey1FRSNghOwtZvYZyD7lEy4FCdTn3InbRq4xXHNSVEdpG0Bbr1MEr/QWin/Q87oabQZo3wyRRJ3KjsO9xCDcwH8xcxUM+I4f3b5zSulpArjBsjkkkMsXih7L35FtzrW241mKjoA5g9/cfbqF7F6Gqwi23eUMCxwbEjgsUdFAKNbSmf9b4b7dAmfwjljM23m6FYGN75r72RH5bSuSoPdNfRwbqtHmvY0dPjcsnBRAkVokNPnvUXx4FMe7ra7T2vFOjfuyrHNVNi82TiOKRbtSxzReyNUOtpAukw833iy0hLyDy/Oo4/9aFXQEg4QSFdb/cZcTUdKE2XWIlstGApXgoy19VfJHJLjFZ7QRQQbd+8l53bZ0vUqpWINpf1UwpgKLLuCKWMqXUlaTfWSTLS+7LAM9PhsSD8FmzwFMJiSlC6ZYmT5W8c74SxRrw0EB8u/UA2UdWaOB7bj66aydOt8i+tu5HhB5eNQGDUh/19seW+48f6Qf5kcwcO/KlEn9hujJbCZA8owbzyT0KFjo5slnvEtH46EKGlaWOrRk4nuDoi3nF87TkLB8yedVxki2dvh8dmTLgGU0Dzb8NpZ+6gq3X+xnXqo92989tQ== me@example.com

3

Copy paste that to the key on your new ssh key form then give it whatever title you like. I gave mine macbook.

4

Done! Now you have added your first ssh key to your github account, now add the other one to another github account or to the same github account giving it a different title so you can differentiate between the two.

Configure SSH

1

On your terminal / CMD PROMPT, run this command: touch ~/.ssh/config this will create a file with the file name of config on the ~/.ssh folder. Now Go to that folder and open that file with your text editor of choice.

2

Copy paste the following on it:

Host gh_work
    HostName github.com
    IdentityFile ~/.ssh/id_rsa_personal

The Host is how you would referrence this credentials on your terminal. The HostName is whatever platform you use, in this case github.com. The IdentityFile is the ssh key to be used for this credential.

Now add another one. By the end you should have something like these:

Host gh_work
    HostName github.com
    IdentityFile ~/.ssh/id_rsa_work

Host gh_personal
    HostName github.com
    IdentityFile ~/.ssh/id_rsa_personal

Testing connection

On your terminal / CMD PROMPT, run ssh -T git@<myHost> replacing myHost with the host you wrote on the config file. Mine is ssh -T git@id_rsa_personal.

After running that command, you should see something like this: Hi <username>! You've successfully authenticated, but GitHub does not provide shell access.. Now you know it's working. Go ahead and test the other key you added.

Cloning repository using a specific ssh key

For this example I will clone this repository: https://github.com/aprilmintacpineda/chat-with-people-backend. To test if yours keys work, you should your own test repository.

Run git clone git@<myHost>:aprilmintacpineda/chat-with-people-backend.git. Replacing myHost with the Host you want that was specified on your config. Ones it's done, you can run git remote -v and you'll see something like this:

origin	git@gh_personal:aprilmintacpineda/chat-with-people-backend.git (fetch)
origin	git@gh_personal:aprilmintacpineda/chat-with-people-backend.git (push)

You see now that it would use my gh_personal keys everytime. Now make changes and commit and push the changes. If all worked well you should get no errors.

Note that if you already have an existing clone in your machine, you can do this:

git remote add origin git@<myHost>:aprilmintacpineda/chat-with-people-backend.git

then simply push to that remote.

Now you're all set, you can test the other key too!

Other Resources

Help me improve this guide by adding comments

Edits and corrections

  • Point out mistakes (even grammatical mistakes).
  • Suggest edits.

Tell me about it

  • Did I missed something?
  • Experiencing an error?

Created with <3 by April Mintac Pineda

@rbtsoliswiki
Copy link

thanks a lot, I'm according with @ewoudtm just edit that part

@tw-yshuang
Copy link

tw-yshuang commented Dec 14, 2021

I create a CLI command to handle this!
Checkout my repo~~
This repo uses ssh-agent to switch your ssh account.

Git_SSH-Account_Switch

A CLI tool can switch an ssh account to your current shell. You will easily switch to your git account & ssh key when using the server, and using your account to manipulate the project on the server.

Installation

$ bash ./setup.sh

it will add some code in your profile & $logout_profile, and setup git-acc & .gitacc on the $HOME.
file:

git-acc.sh -> $HOME/.git-acc, git-acc function.
.gitacc -> $HOME/.gitacc, save info. that regist on git-acc.

Control

        +---------------+
        |    git-acc    |
        +---------------+

SYNOPSIS

  git-acc [account]|[option]

OPTIONS

  [account]               use which accounts on this shell, type the account name that you register.
  -h, --help              print help information.
  -add, --add_account     build git_account info. & ssh-key.
      -t, --type          ssh-key types, follow `ssh-keygen` rule, 
                          types: dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa(default)
  -rm, --remove_account   remove git_account info. & ssh-key from this device
  -out, --logout          logout your current ssh-acc.


EXAMPLES

  $ git-acc tw-yshuang

@cooljetdi
Copy link

Don't you need to add each SSH key to the SSH agent first?

@tw-yshuang
Copy link

tw-yshuang commented Dec 28, 2021

Yes, it needs to add a SSH key in the first, you can type git-acc -add, and it will generate a SSH key automatically. btw, you can set a password at this moment.
Next time you want to use your git-acc and SSH key, just type git-acc <tab>, and it will autocomplete to find your register account.

Hope you enjoy using this tool~~

@jamesbroucek
Copy link

This helped me. Thanks!

Is there a mistake in the "testing connection" section? you wrote: "On your terminal / CMD PROMPT, run ssh -T git@ replacing myHost with the host you wrote on the config file. Mine is ssh -T git@id_rsa_personal."

But <id_rsa_personal> is your ssh key name. Your host is . Right?

@umar-musashi
Copy link

Thank you for clarifying what the ssh config variables do!

@umarxfhu
Copy link

umarxfhu commented Mar 2, 2022

Great gist! Clarifying what the ssh config variables do was a nice touch.

@EasySigh
Copy link

EasySigh commented Mar 14, 2022

Thanks a lot!

@meli07-sudo
Copy link

It's doesn't exist a simple way to use all ssh keys for a single hostname ?
Or use many identityfile for one ?

@KnifyMan
Copy link

KnifyMan commented May 6, 2022

Best guide I've read in a month, thanks a ton

@liorosh
Copy link

liorosh commented May 23, 2022

I spent an entire day trying to accomplish having multiple accounts on my machine and this is the only guide that managed to make it work!
THANK YOU!

@JeHwanYoo
Copy link

Nice work

@KGuetfade
Copy link

KGuetfade commented Sep 5, 2022

ssh -t git@[host] works however when I try to fetch from my remote url git@[host]:[remote username]/[repo name].git it says

Unable to open connection:
Host does not existfatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Any idea why this is happening?

edit: I have my ssh config file setup, added the keys using ssh-add and ssh -T git@[host] works however any git command with the correct remote url does not

@vehicle2a
Copy link

Awesome guide -- thanks a lot for posting this

@torrespro
Copy link

torrespro commented Oct 11, 2022

Really useful! Just some details

https://gist.github.com/aprilmintacpineda/f101bf5fd34f1e6664497cf4b9b9345f#2-1

Host gh_work
HostName github.com
IdentityFile ~/.ssh/id_rsa_personal //should be _work right?

https://gist.github.com/aprilmintacpineda/f101bf5fd34f1e6664497cf4b9b9345f#testing-connection

On your terminal / CMD PROMPT, run ssh -T git@ replacing myHost with the host you wrote on the config file. Mine is ssh -T git@id_rsa_personal //should be git@gh_personal right?

Here my fixes: https://gist.github.com/torrespro/e77413a27bdf0b35ef9f71dfda41e1de/revisions#diff-758725cb92ccbb462fe8481f107e068e671061ed9857b785cfa5216226d9b763

@adminka-root
Copy link

@ajesaramos
Copy link

Your guide works perfect! Thank you!

@ndemarco
Copy link

ndemarco commented Jul 15, 2023 via email

@berryjam
Copy link

Thanks a lot!It works for me.

@Amleto
Copy link

Amleto commented Nov 10, 2023

Thanks for this guide!

@RadiationDark
Copy link

Thanks man. Superb guide.
Just a little grammatical mistake under the heading "Cloning repository using a specific ssh key".
You should change " To test if yours keys work, you should your own test repository" to "To test if your keys work, you should test on your own test repository."

@jiapeish
Copy link

Thank you! I met an error Please make sure you have the correct access rights and the repository exists. and finally solved it.

If you use ssh-agent cache, you should invalidate the cache and then add the keys again

  1. Invalid old cache
ssh-add -D
  1. Add new generated keys to cache
$ ssh-add ~/.ssh/id_rsa_work
$ ssh-add ~/.ssh/id_rsa_personal

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment