Hello, this post will be about how to use several ssh keys in a “simple” way.
I had the problem of having several ssh keys to connect to different servers and also to use git with a different key.
I know I’m not quite clear with this, so let’s take an example.
You have two keys, one to connect to a server and an other one to use git (github, bitbucket, whatever …).
You want to clone a project using git :
git clone firstname.lastname@example.org:/myAwesomeProject
And you would do this to connect to the server s1.farm.florianleleu.com :
ssh email@example.com -p 2222
Your keys are in ~/.ssh/, though which one will be used for the server and which one for git? Stuck.
I hope it’s more clear now. 😀
Here’s one way to solve this problem.
You have to create this file ~/.ssh/config
Give it some “good” rights (i.e chmod 600 ~/.ssh/config)
Here is an example of what you can write in this file, the explanations will follow :
Host git git.florianleleu.com HostName git.florianleleu.com User git IdentityFile ~/.ssh/git/id_rsa Host *.farm.florianleleu.com User florian Port 2222 IdentityFile ~/.ssh/farm/id_rsa
Options shown :
- Host => alias or the pattern(s) you want to match, some regex are allowed
- Hostname => the real host you want to connect to
- User => the user with which you will be connected on the remote server
- Port => the port of the remote server (default 22)
- IdentityFile => the path to your private key
And now how to use it :
git clone git:/myAwesomeProject
In this command: git clone git:/myAwesomeProject, what’s in bold will be replaced by firstname.lastname@example.org because it is matched by the first Host (i.e alias), and obviously, it will do what was wanted at first, which is to take the key ~/.ssh/git/id_rsa. Note that you can also write it git clone email@example.com:/myAwesomeProject, but the alias is quite handy.
In this command: ssh s1.farm.florianleleu.com, it’s matched by the second Host, and will be replaced by firstname.lastname@example.org -p 2222 and use the file ~/.ssh/farm/id_rsa.
Obviously, not everything is said, there are other options ! RTFM 🙂