BytesOfProgress

Wiki


Shorten SSH Commands with config

This will be all about less typing. When we normally connect to a machine via SSH, we type something like this:



  $ ssh [email protected]

or:


  $ ssh user@ip-address


But when we connect to a server quite often, this will get annoying quickly. We can use a config file to make establishing a connection much easier and faster.

In most distributions, this config file has 2 locations: "/etc/ssh/ssh_config" for system-wide config, and "~/.ssh/config" for only the user. Some distributions might only have the system-wide config. In most cases, if the user's file is non-existent, you can just create it and it will work just fine. Yes, we could also create aliases for some of these configs in our ~/.bashrc, but it is considered good practice to use the ssh_config.


Hostname alias config


  Host test
    HostName ssh.domain.com

This will shorten the command from the beginning to this:



  $ ssh user@test


You can also create multiple hostname aliases for the same host, like this:


  Host test sample dummy
    HostName ssh.domain.com

With this config we can either use test, sample or dummy in our SSH command to connect to the same machine.

If the server has multiple subdomains you would like to be able to use in your command, you can use hostname aliases like this:


  Host test sample dummy
    HostName %h.domain.com

With this, you can use test, sample or dummy in your SSH command, and SSH will hang put your alias as the subdomain for the host. For example:



  $ ssh user@test # This will connect you to test.domain.com



  $ ssh user@sample # This will connect you to sample.domain.com


Pre-configuring the username


We can shorten the command even further by pre-configuring the user in the config file. This will come in handy if you always connect to the machine as the same user.


  Host test
    HostName ssh.domain.com
    User admin

With this config you would connect to "ssh.domain.com" as the user "admin", just by typing this command:


  $ ssh test





back