Simplify Your Life With an SSH Config File
by jperras
If you’re anything like me, you probably log in and out of a half dozen remote servers (or these days, local virtual machines) on a daily basis. And if you’re even more like me, you have trouble remembering all of the various usernames, remote addresses and command line options for things like specifying a non-standard connection port or forwarding local ports to the remote machine.
Shell Aliases
Let’s say that you have a remote server named dev.example.com, which has not been set up with public/private keys for password-less logins. The username to the remote account is fooey, and to reduce the number of scripted login attempts, you’ve decided to change the default SSH port to 2200 from the normal default of 22. This means that a typical command would look like:
password: *************
Not too bad.
We can make things simpler and more secure by using a public/private key pair; I highly recommend using ssh-copy-id for moving your public keys around. It will save you quite a few folder/file permission headaches.
# Assuming your keys are properly setup...
Now this doesn’t seem all that bad. To cut down on the verbosity you could create a simple alias in your shell as well:
$ # To connect:
$ dev
This works surprisingly well: Every new server you need to connect to, just add an alias to your .bashrc (or .zshrc if you hang with the cool kids), and voilà.
~/.ssh/config
However, there’s a much more elegant and flexible solution to this problem. Enter the SSH config file:
Host dev
HostName dev.example.com
Port 22000
User fooey
This means that I can simply $ ssh dev, and the options will be read from the configuration file. Easy peasy. Let’s see what else we can do with just a few simple configuration directives.
Personally, I use quite a few public/private keypairs for the various servers and services that I use, to ensure that in the event of having one of my keys compromised the dammage is as restricted as possible. For example, I have a key that I use uniquely for my github account. Let’s set it up so that that particular private key is used for all my github-related operations:
HostName dev.example.com
Port 22000
User fooey
Host github.com
IdentityFile ~/.ssh/github.key
The use of IdentityFile allows me to specify exactly which private key I wish to use for authentification with the given host. You can, of course, simply specify this as a command line option for “normal” connections:
but the use of a config file with IdentityFile is pretty much your only option if you want to specify which identity to use for any git commands. This also opens up the very interesting concept of further segmenting your github keys on something like a per-project or per-organization basis:
User git
HostName github.com
IdentityFile ~/.ssh/github.project1.key
Host github-org
User git
HostName github.com
IdentityFile ~/.ssh/github.org.key
Host github.com
User git
IdentityFile ~/.ssh/github.key
Which means that if I want to clone a repository using my organization credentials, I would use the following:
Going further
As any security-conscious developer would do, I set up firewalls on all of my servers and make them as restrictive as possible; in many cases, this means that the only ports that I leave open are 80/443 (for webservers), and port 22 for SSH (or whatever I might have remapped it to for obfuscation purposes). On the surface, this seems to prevent me from using things like a desktop MySQL GUI client, which expect port 3306 to be open and accessible on the remote server in question. The informed reader will note, however, that a simple local port forward can save you:
# -f puts ssh in background
# -N makes it not execute a remote command
This will forward all local port 9906 traffic to port 3306 on the remote dev.example.com server, letting me point my desktop GUI to localhost (127.0.0.1:9906) and have it behave exactly as if I had exposed port 3306 on the remote server and connected directly to it.
Now I don’t know about you, but remembering that sequence of flags and options for SSH can be a complete pain. Luckily, our config file can help alleviate that:
HostName database.example.com
IdentityFile ~/.ssh/coolio.example.key
LocalForward 9906 127.0.0.1:3306
User coolio
Which means I can simply do:
And my local port forwarding will be enabled using all of the configuration directives I set up for the tunnel host. Slick.
Homework
There are quite a few configuration options that you can specify in ~/.ssh/config, and I highly suggest consulting the online documentation or the ssh_config man page. Some interesting/useful things that you can do include: change the default number of connection attempts, specify local environment variables to be passed to the remote server upon connection, and even the use of * and ? wildcards for matching hosts.
I hope that some of this is useful to a few of you. Leave a note in the comments if you have any cool tricks for the SSH config file; I’m always on the lookout for fun hacks.
Comments
Pretty sweet man…I could definitely use this! Thanks for taking the time to blog it.
Great article, very helpful.
I think you have an error in your tunnel example :
LocalForward 9906:127.0.0.1:3306
Should be :
LocalForward 9906 127.0.0.1:3306
At least that’s how it is specified in the documentation and how it works on my machine. Thanks for the article, it was very helpful.
@Bertrand: Fixed – thanks for pointing that out!
While I don’t use multiple keys for github, I do like simplifying the clone URL, since I find myself cloning them often:
Host gh
Hostname github.com
User git
Thusly the clone url is:
gh:jperras/vim-dotfiles.git
Very nice post! Definitely made my day easier. Thumbs up :)
Fantastic write up. Thanks for writing the article.
What do you use to do the syntax highlighting?
@Arunabh: It’s basically GeSHi: http://kpumuk.info/projects/wordpress-plugins/codecolorer/
Thank You …
A minor edit: Under “Shell Aliases”, the narrative refers to port “2200″, but the screen shots display port “22000″.
Good job…
:-)
–majickmann
What do I put on my remote server so that only I can ssh from my machine at home? Akin to
hosts.allow
sshd: 1.2.3.4
Is there (on remote) ~/.ssh/hosts.allow
Thanks.
Great post. I’ve already refactored how I access some servers. I was super excited to see this:
$ alias dev=’fooey@dev.example.com -p 22000′
$ # To connect:
$ ssh dev
However, I was unable to get my alias to ‘expand’ after the ssh command. I’m using bash and I wasn’t sure if there’s some config or other shell trick you did to get this to play nice. Thx!
Nicely explained… It was very useful.
Thank you very much.
Thanks Joel. The post was quite helpful and explanatory.
It was useful.. thanks..
Thank you, it is very helpful
Great write-up.
Is there a way to set the PATH variable in my remote machine using ssh config ? Might sound a bit odd.
My trouble is, the kshrc file isn’t sourced/read when I ssh, reason being that the location of my user profile is in a different directory. Thus the PATH var is not getting set when I do ssh, and not able to do any git clone from my remote server.
Thanks.
This is amazing man, I really enjoy doing and learning a lot from your blog post ;)
Great article… exactly what i needed
simple, beautifully written. Thankyou.
mc
Really helped me understand how the ssh config file works. Best article for newbies I have seen so far. Thanx a lot!
In your last example under ~/.ssh/config since you specified the user in the config file you don’t need to mention the user in the ssh command. Also the .git extension is not required hence you can simply issue the following command: git clone github-org:orgname/some_repository
Is there a possibilty to add an entry for a host which is only reachable through another ssh tunnel, and open this tunnel automatic ?
atm i have to:
ssh tunnel
and on a second shell
ssh host_which_is_only_reachable_through_tunnel
better would be only to
ssh host_which_is_only_reachable_through_tunnel
Greetings from Cottbus ! ;)
Thanks for this well summarized how-to on setting up the ssh config with public key support.
Very nice post!
Very neat. Thanks for this, I can now stop going to a wiki to look up hostnames.
thanks for putting all of this together! I have done each one of these things sparingly (when needed), but always forget to document it once it’s done. 6 months later, I forget where everything was configured!
Having it all in the ssh config is the way to go, and I’ll definitely be bookmarking this as reference for my team :)
pretty sure you can shorten this:
git clone git@github-org:orgname/some_repository.git
to this:
git clone github-org:orgname/some_repository.git
since you included your username in the config
Small erratum:
Your ‘alias’ example wouldn’t actually work. You should either do:
export dev=’fooey@dev.example.com -p 22000′
ssh $dev
or:
alias dev=’ssh fooey@dev.example.com -p 22000′
dev
(Aliases are only resolved in place of commands, not arguments.)
Other than that, awesome!
One ssh flag I haven’t yet found how to specify in my ssh config file is -t (for “Force pseudo-tty allocation”.)
This is required for e.g. connecting to a remote running screen session:
ssh -t dev screen -DRU
The shell ‘alias’ method doesn’t work, either in bash or zsh, and I don’t see how it could – aliases only work when they are the first thing in the command, which is a very good thing (otherwise you wouldn’t be able to manipulate files called the same things as one of your aliases, for example).
Nice article, I like to remember ports and usernames, and I just login in around 25 servers so is enough to memorize :)
I am wondering what do you mean by “or .zshrc if you hang with the cool kids”
Oh, just that ZSH is the new cool shell that people use (myself included) instead of Bash, and .zshrc is the equivalent of .bashrc. Nothing more than that ;-).
Also, thanks to the people that pointed out my section on command aliasing contained an error. It has been fixed. Thanks!
I have come to the conclusion that using multiple public/private key pairs for different servers is superfluous. The only key that leaves your computer is the public key, which does not need to be secured… that’s the magic of public key algorithms. You can publish your public key on craigslist and your ssh is still just as secure!
If it were really possible to compromise a private key by knowing the public key, then the internet has many many bigger security problems, and much more lucrative targets than anything that you’re protecting.
Much easier and just as secure to use a single public key pair.
@rupat, sure. ssh itself takes arguments as commands to run on remote hosts. after glancing at the ssh_config man page however, there isn’t an accommodation for this. so you’d have to use an alias, e.g.:
alias access_firewalled_host=’ssh user@accessible_host ssh user@inaccessiblehost’
that would run ssh on the remote host after connecting. if you’ve setup key authentication between yourself and the accessible host, and then the accessible host and inaccessible host you’ll get straight in.
you could also establish a tunnel via SSH between the two machines and access that, or if you really want to piss off your network administrator, check out using something like netcat to bounce a port on the outside machine to ssh on the inside network.
best of luck!
@rupat: you looking for the ProxyCommand option to SSH which allows you to ssh to a gateway or other midpoint server and then ssh from there to a remote host that is not reachable except through that gateway
Here are some good references:
http://serverfault.com/questions/37629/how-do-i-do-multihop-scp-transfers
http://benno.id.au/blog/2006/06/08/ssh_proxy_command
You can shorten those commands even further; just grab a copy of the “ssh-argv0″ command, and make symlinks to it named after your SSH config file aliases. So, if you link dev -> ssh-argv0, you can just type “dev” rather than “ssh dev”.
Immediately put this info to good use. Thanks for the write up :)
Neat. Will save lot of time for me. I usually open 4 to 5 sash connection to various servers on daily basis. This eases my work.
By the way is it possible to make connections to set of servers automatically once terminal opens?
I reallly like to create Reverse SSH Tunnels on the fly . If you already logged in a host:
(Press Enter, to get a new line)
$ ~C
ssh> -R 4000:localhost:22
Forwarding port.
$ scp -P 4000 file.tar.gz localhost:/path/to/laptop
It’s very handy if you want to get some files.
Nice write up!!
One of the better articles I’ve read in a long time. Thanks.
Great idea to put tunneling info config, because I always have to look up those commands when I do it every once in a while.
I use a combination of .ssh/config and aliases. The former contains all the information necessary to connect to a server (host name, port, user name etc.) – the latter usually first try to connect to an existing tmux session which goes by the very uninspired name “default”*, all encapsulated by a short name that is used both for the SSH host and shell alias.
Since I tend to update shell stuff and SSH stuff separately I put the alias setups in .ssh/profile and my .profile (which in turn is sourced by my .zshrc) has a line:
[ -f ~/.ssh/profile ] && . ~/.ssh/profile
SSH will just ignore it but all the SSH-hosts-specific information is therefore contained within .ssh
The result is that I can do “xx” to connect to a server regularly (and pick up my tmux session), or “ssh xx” to do a plain connection, “scp xx:foo bar” etc. pp.
* the alias lines all look like
alias xx=”ssh xx -t ‘tmux attach -d -t default || tmux new-session -s default’”