Several recent projects have required different SSH keys for different Git configurations. The following uses adding multiple SSH keys on Github as an example.

Create multiple SSH keys

Create an SSH key

$SSH -keygen -t rsa -c "[email protected] "-f ~/. SSH /id_rsa_personalCopy the code

Create a second SSH key with the same command but a little different

$SSH -keygen -t rsa -c "[email protected] "-f ~/. SSH /id_rsa_companyCopy the code

Add the public key

Add the private key

ssh-add ~/.ssh/id_rsa_company
ssh-add ~/.ssh/id_rsa_personal
Copy the code

If “Could not open a connection to your authentication agent” is displayed when you run the ssh-add command, run the command first

$ ssh-agent bash
Copy the code

Then run the ssh-add command again. After success, the picture is as follows:

View the private key list

$ ssh-add -l
Copy the code

Clear the private key list

$ ssh-add -D
Copy the code

Add a key to Github

Log on to Github or your code hosting platform. In the upper right corner, log in to your profile and click SettingsClick on the SSH keys Click on theAdd Key, complete adding

Create and modify the config file

In Windows, create a TXT file and rename it config. Note that there is no suffix as follows:

company github

Host company.github.com HostName github.com PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa_company User git

personal github

Host personal.github.com HostName github.com PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa_personal User git

Configuration File Description

HostName: specifies the name of the Host to be logged in to. It must be valid, for example, github.com. User: specifies the SSH key file path. Port number (required if not the default port number 22)

If I want to clone my personal code base, do it

git clone [email protected]:USERNAME/PROJECT.git
Copy the code

Git libraries are translated this way

Git @${Host}:USERNAME/ project. git # ${Host} will be replaced with HostNameCopy the code

For example, https://github.com/Kitware/CMake.git

test

$SSH -t [email protected] PS: debug github, ssh-vt [email protected] -v Then use the compiled information to solve the problem yourself. In my case, the host block in config is written wrong

If you have set the global username and mailbox before, you need to unset it

git config --global--unsetuser.name
git config --global--unsetuser.email
Copy the code

Then set up local usernames and mailboxes in different repositories such as the company repository

git config user.name "yourname"  
git config user.email "youremail"
Copy the code

Execute the command just one more time in your github repository. In this way, you can log in with different accounts in different warehouses.

Reference 1 Reference 2