Ssh – Only apply Match keyword to single Host in ssh config

opensshsshssh-config

I have a host which I ssh into. Sometimes I'm inside the same network, and can ssh directly into it, other times I'm outside it and I need to use a proxy.

Because ssh via the proxy server is much slower than direct, I'd like to have my ssh config set up such that I try to connect directly, falling back to the proxy if that fails.

Currently the config looks like:

    Host proxy_server
    User user
    Port port
    Hostname some_domain

    Host target_host
    User user
    Port port
    Hostname ip_addr_of_host
    Match exec not_inside_network
    ProxyCommand ssh -W %h:%p proxy_server

The target_host entry is the last entry in my config file, yet not_inside_network gets called by any ssh connection to unrelated servers in the config file. How can I make Match only apply to this one server?

Best Answer

Match is rather on-par with Host. It doesn't exist as a subset of Host the way other options do.

But you can specify multiple criteria on a match, and they appear to operate as a short-circuit AND. So this should be possible and useful for you:

Match host target_host exec not_inside_network
    ProxyCommand ssh -W %h:%p proxy_server

This rule will be checked on every ssh. But for hosts not matching "target_host", the match immediately fails and moves to the next Match or Host keyword (if any). Only if the host is "target_host" will the exec occur. Then the truth of that statement will determine whether or not the ProxyCommand is invoked.

To see the logic occur, run with -vvv. You should see some match checks at debug3.

Related Question