At work, I often have to log into hosts which follow a common naming scheme, e.g. qc01 - qc12, hc01 - hc10, and so on. All of these need to get the same config values in my laptop's .ssh/config. Of course, I could use entries for the hosts qc* and hc*, but I'm wondering if instead it is somehow possible to use regular expressions?


4 Answers 4


As gelraen stated default ssh_config won't support regular expressions but you can try something different like :


You can use full regular expressions in your ssh_config.

The relevant documentation is IMO very hard to read and understand. I only understand it because I have 13+ years Linux experience and and 8+ years using ssh. So here is my summary of the documentation:

  • man ssh_config describes a feature called Match
  • then there is a feature called exec which let's you use an arbitrary shell command for determining a match
  • passing input parameters to the arbitrary shell command is possible and described in the section labeled TOKENS

In my case i ended up using in my ~/.ssh/config:

Match exec "echo %h | grep -q 'NAME[0-9]\+$'"
    User USER
    IdentityFile /path/to/identity/file
    Hostname %h.fully.qualified.domain.name

Testing must be done with something tricky like this. And to do that testing you call ssh -vvv HOSTNAME. Which will show exactly what is happening, and whether your new Match is implemented correctly.


Please, see PATTERNS section in man ssh_config.

Long answer is: No, you can't, unless you patch your ssh to support that.


Extending the answer from Trevor:

More complex hosts are also possible, like matching foo123.123 and foo10.10 in one rule WITHOUT having DNS entries for the used hostnames:

Match exec "echo %h | grep -q 'foo[0-9]\+.[0-9]\+$'"
    Port 1234 # just to show it can be paired with non-default ports too,
              # see %p in man ssh_config
    ProxyCommand /usr/bin/nc 10.10.$(echo %h | sed -e 's/foo//') %p

Using the ProxyCommand to manipulate the content of %h with the shell and connecting to the right port through a netcat. This way you can create presets for category of hosts, without creating individual entries.

  • 1
    This looks great, but I can't get it to work. I specified the port as fixed (22), but ssh -vvv gets stuck on "debug1: Local version string SSH-2.0-OpenSSH_8.1" for a while and then prints "kex_exchange_identification: Connection closed by remote host". Any pointers? :) Commented Nov 22, 2020 at 12:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .