create a different ssh key for each account (GitHub, GitLab, ...)
$ ssh-keygen -t rsa -C "your_email@youremail.com" -f ~/.ssh/github-github_user_name
$ ssh-keygen -t rsa -C "your_email@youremail.com" -f ~/.ssh/gitlab-gitlab_user_name
for example, 2 key pais created as follows:
~/.ssh/github-github_user_name
~/.ssh/github-github_user_name.pub
~/.ssh/gitlab-gitlab_user_name
~/.ssh/gitlab-gitlab_user_name.pub
all cached keys can be deleted before
$ ssh-add -D
If you get the following error: "Could not open a connection to your authentication agent."
Try this:
$ eval "$(ssh-agent)"
add these two keys as following
$ ssh-add ~/.ssh/github-github_user_name
$ ssh-add ~/.ssh/gitlab-gitlab_user_name
create the config file if it does not exist and open it using a text editor (vi / vim / gedit / nano...)
$ cd ~/.ssh/
$ touch config
$ vim config
add all the accounts
#github-github_user_name account
Host gh-github_user_name
HostName github.com
User github_user_name
IdentityFile ~/.ssh/github-github_user_name
#gitlab-gitlab_user_name account
Host gh-gitlab_user_name
HostName gitlab.com
User gitlab_user_name
IdentityFile ~/.ssh/gitlab-gitlab_user_name
finally, check the saved keys
$ ssh-add -l
if the ssh keys don't show up, run:
$ ssh-add ~/.ssh/github-github_user_name
$ ssh-add ~/.ssh/gitlab-gitlab_user_name
one of the following methods (A or B) is used
the git username and email can be set globally and then use the normal flow to push the code
while working with GitHub
$ git config --global user.name "github_user_name"
$ git config --global user.email "your_email@youremail.com"
while working with GitLab
$ git config --global user.name "gitlab_user_name"
$ git config --global user.email "your_email@youremail.com"
clone the repository
$ git clone git@github.com:github_user_name/repo.git repo-github_user_name
if repo-github_user_name
is not defined at then end of the command, the folder name will be same as the repo
name.
enter the repository folder and modify the git configuration locally
$ cd repo-github_user_name
$ git config user.name "gibhub_user_name"
$ git config user.email "your_email@gmail.com"
$ cd repo-gitlab_user_name
$ git config user.name "giblab_user_name"
$ git config user.email "your_email@gmail.com"
then use normal flow to push the code
$ git add .
$ git commit -m "your comments"
$ git push
If you want to connect to your machine via SSH, you can be sure that your ISP or router does not block this protocol and its port by using the following:
$ ssh -T git@github.com
For more use Testing your SSH connection by GitHub
This is a customized version of Multiple SSH Keys settings for different GitHub account documented by jexchan