Unix – find more SSH power with ssh config

keys-banner

Do you want to use multiple key pairs for github and servers ? Ever wondered how people just type ‘ssh myserver’ and it automagically connects ? you will know some cool methods after next few minutes

Normally, you can use alias to connect to server with fewer keystrokes

alias myserver='ssh user@yourhost.com -p 37000'
# To connect using this alias, just type
myserver

This works fine. you can have a list of shortcut if you add aliases for all your servers in .bashrc (or something like that if you use other shell)

But this is not the ssh way, using this method, you can’t achieve 1st goal : ‘use multiple key pairs for github and servers’. you can achieve 1st goal and have a nicer approach for 2nd goal with ssh config

Create an SSH config file
To create an SSH config file, open your terminal and issue the following command:

vi ~/.ssh/config

If you’re a little unsure of vi, replace it with your favourite editor, such nano.

In the same file, copy and paste the following lines:

Host myserver
  HostName myserver.com
  User root

You’re done! Save the file and open your new SSH session by typing:

ssh myserver

At this point, you have a nicer ssh shortcut, but how to connect to github with multiple keys ? we will need another key pair first

generate new ssh key

ssh-keygen -t rsa -f ~/.ssh/id_rsa_deploy -C "comment for this key"

then add these line to you SSH config file

Host github.deploy
User git
HostName github.com
#use specific ssh key file for this Host (github.deploy) - so we can use it like this : git clone git@github.deploy:[repos name]
IdentityFile ~/.ssh/id_rsa_deploy

Host github.com
User git
IdentityFile ~/.ssh/id_rsa
#Port 22     # you can specify port for your host too

Which means that if I want to clone a repository using my deploy credentials, I would use the following:

git clone git@github.deploy:orgname/some_repository.git

congratulation, you have done it!

Note for Mac OS X : you will need to killall ssh-agent in order to reload config. May be you will need to use this command to see what you need to kill actually (ssh-agent or sshd)

launchctl list

then use this command to kill process

killall ssh-agent