Lucas Courot

A proper way to manage your SSH hosts

Posted on by

If you've ever wondered how to connect to two different hosts each having its own public/private keys or how to avoid to always type the login / port info of your ssh server, then keep reading...

The best way I found to organise SSH hosts is to use the SSH configuration file located under the home directory (~/.ssh/config).

If it doesn't exist, you can create it.

$ mkdir ~/.ssh/
$ chmod 700 ~/.ssh/

$ touch ~/.ssh/config
$ chmod 600 ~/.ssh/config

Here is an example of the configuration file

Host example
    HostName example.com
    User git
    IdentityFile ~/.ssh/example_rsa
    IdentitiesOnly yes

Host projectname
    HostName projectname.co.uk
    User projectname
    Port 2222

Host heroku
    Hostname heroku.com
    User git
    IdentityFile ~/.ssh/heroku_rsa
    IdentitiesOnly yes

You have to provide a Hostname which is the domain name or the IP of your host and an ssh User. You may specify a Port number if your server is expecting you to connect on a different port than the default (eg port 2222 instead of port 22). If you connect with your private key, then use IdentityFile to provide its path. IdentitiesOnly yes causes SSH to only use the specified identity file.

Now you can just type ssh projectname instead of ssh projectname@projectname.co.uk -p 2222.

Also you can use the git clone example:/path/totherepo.git command to clone your git repository. And no need to tell how easy it is to configure a multi-account connection for platforms such as github, bitbucket, heroku etc.

Of course, you can autocomplete the host names ssh ex<tab>.

For more info, have a look at man ssh_config.

See the other articles published in Linux .