Utilize Bash Aliases for Quicker SSH Connects

If you find yourself constantly connecting and disconnecting to different computers using SSH it is useful to setup aliases to speed up this process. There are a few ways of doing this, including creating a config file within your .ssh directory and using the .bashrc file to create aliases on boot-up. Okay, lets get down to the nitty – gritty.

1. Setup A ‘config’ File In Your .ssh Directory

For those computers that you plan to connect to quite often, create a config file in ~/.ssh. Otherwise known as your home directories .ssh folder.

:~/.ssh$ cat config 
Host data
    User erik
    HostName 192.168.12.45
    Port 22
    ForwardX11 yes
 
Host htpc
    User erik
    HostName 123.17.51.92
    Port 22
    ForwardX11 yes
 
Host orion
   User gregor
   HostName 192.16.22.134
   Port 22
   ForwardX11 yes

Take note of the Host name. These will be used as aliases to the HostName IP address, so rather than typing the IP address you can simply type the name.

2. Add Bash Code To Create Aliases on Boot

Now lets head over to your .bashrc file and add a simple line which will use the config file above to create aliases for quick ssh usage. At the end of your .bashrc file add this line:

for name in `sed -n "/^Host/s/^Host //p" ~/.ssh/config`; do alias $name="ssh $name"; done

Breaking this down, we cycle through the config file from the .ssh directory and create an alias for each pairing. So each alias will be orion=ssh orion. Lets check the aliases:

alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias data='ssh data'
alias grep='grep --color=auto'
alias htpc='ssh htpc'
alias ls='ls --color=auto'
alias orion='ssh orion

This simple substitution will replace orion with the ssh orion. In doing so, SSH will check the config file within the .ssh directory and substitute the HostName with the actual IP address, and voila.

3. Execute SSH

Now executing the command:

$ htpc erik@123.17.51.92’s password:

If I had already copied my authorized key to the server, then I would not even be prompted for the password. This simple setup saves a lot of time, especially if you find yourself constantly connecting and disconnecting from remote servers, or have to copy files back and forth a lot. You can simple run commands like:

$ scp data.txt htpc:/tmp/

This is a lot nicer than having to remember the IP address and which username is for that server.