SSH – Dynamically Generate Host Entries in ~/.ssh/config

ssh

I have to administer a whole pile of hosts over ssh. However I can only access them through a certain gateway ssh server.

I have the following in my ~/.ssh/config:

Host mygateway-www
Hostname www
IdentityFile ~/.ssh/id_rsa
ProxyCommand ssh mygateway nc %h 22

However I have to connect to lots of these machines. Instead of putting dozens of entries in my ~/.ssh/config, is there anyway I can have something like this:

Host mygateway-*
Hostname ???WHAT GOES HERE????
IdentityFile ~/.ssh/id_rsa
ProxyCommand ssh mygateway nc %h 22

I know you can use %h in the Hostname argument, but that would be the hostname. What I really need is some sort of string substitution, like bash's ${VAR%thingie}. Is this possible?

Best Answer

This can be done with the following SSH config file:

Host *
  ServerAliveInterval 120

Host gateway.somewhere.com
  User jdoe

Host gateway+*
  User jdoe
  ProxyCommand ssh -T -a $(echo %h |cut -d+ -f1).somewhere.com nc $(echo %h |cut -d+ -f2) %p 2>/dev/null
  ControlMaster auto
  ControlPath ~/.ssh/ssh-control_%r@%h:%p

You then access your internal hosts like so:

ssh gateway+internalhost01.somewhere.com
ssh gateway+internalhost02.somewhere.com

The name you choose for the right half should be resolvable by the jump host.

The User parameter is specified in case you need to manually map to different users on the different classes of hosts. ControlMaster and ControlPath are specified to allow SSH connection re-use.