ASCII Thoughts

SSH Config & Aliases

SSH is a wonderful tool. It has many advanced features which can make your life easier as a developer, but they are not always well known or understood. So today, let's introduce one of these: aliases.

When you are working on a project, you often have to switch between different servers: a local server, a test/staging server and a production server. So you find yourself typing this all day:

ssh user@virtual-machine

Some people find a workaround with shell aliases:

alias test="ssh"

That works alright in most cases, but what happens for example when you have to use scp or a rsync: you have to type the full command again...

# SSH to production server, quick and easy

# Copy a file from test server. #FAIL
scp .

The solution

Thankfully, SSH offers aliases too. They are defined in ~/.ssh/config:

Host foo
  User user

With that configuration in place, you can now do all of the following:

# ssh
ssh foo

# scp /bar
scp foo:/some/path /bar

# rsync /bar
rsync foo:/some/path /bar

All servers in a project

I follow a convention for all my servers and use suffixes to identify which server I'm connecting too. So let's say I want quick access to all the environments of my project example. Here is what my config would look like:

  User deploy
  Hostname virtual-machine

Host example.test
  User deploy

  User deploy

This way, I can quickly go to any of those servers, and I don't have to remember their exact name, IP address, login, etc.:

ssh    # local vm
ssh example.test   # testing server
ssh   # production server

Of course, the following now works too:

rsync -avz example.test:/var/www path

Other options

You don't have to limit yourself to User and Hostname, you can use the full range of SSH options. Here is a more advanced configuration:

Host example
  Port 678
  User special
  LocalForward 8000
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/id_example_dsa
  Compression yes

You can find more information about the options available and the general format of the file in the man:

man ssh_config


SSH aliases can dramatically ease your life. Use them!

Until next time, Cheers!