How to Make Shortcuts to SSH into your Servers
I have written in the past several times about how to alias commands in the terminal to speed up certain tasks. Today, I have another thing that I like to set up on my machines that save a bunch of time.
Like a lot of developers, I have access to several different servers and often have to access them. Who can be bothered to, every time they want to ssh into a server, try to remember the IP address, the user and the ssh key for a particular server, and then type the whole command out - especially when trying to access it under pressure (e.g. apache2 urgently needs restarting or something)?
This is where the ssh config file can come in useful.
Inside the .ssh
folder where you keys should be, create (or open if it is already there) a file called "config". Inside this, you can put configurations for all of your servers. For example:
Host someServer
User my_user
HostName 12.34.56.789
Port 22
IdentityFile ~/.ssh/ssh_key.pem
Note the 4 space indentations. If you have multiple servers, these would just be additional blocks underneath.
The name next to Host
can be whatever you want. I think the other settings are fairly self explanatory.
Save the file and you will now be able to do:
ssh someServer
Which in this case would be the equivalent of:
ssh -i ~/.ssh/ssh_key.pem my_user@12.34.56.789
See how much easier that is!
Now I like to go one step further.
I often find that if I enter a server, I have to cd
into a specific folder every single time. So, I can write a new line in my .bash_profile
(as described in my previous guide here):
alias sshmyserver='ssh -t someServer "cd /var/www/ ; bash"'
This means that I can now just run:
sshmyserver
And it will log me in and set me down in the /var/www/
folder.
This example goes from 59 keystrokes to just 11 (more than 80% reduction) and gets rid of the need to remember IP addresses and server details.