Can you configure per-network SSH settings?

I'm talking about ssh_config(5). I wonder if you can define a config section or file based on the currently connected network.

I'm thinking about that scenario where the corporate firewall blocks port 22, but your home network doesn't. So, you have this configuration, but it's technically unnecessary at home.

Host github.com
  Hostname ssh.github.com
  Port 443

I'm sure this isn't the most interesting scenario, but I hope you can see what I'm getting at.


I have solved this by having multiple configs named by DHCP-provided domain plus one default as a fallback, e.g. ~/.ssh/config.abc, ~/.ssh/config.xyz, ~/.ssh/config:default for two domains abc and xyz, plus default. If you are wondering why colon in default -- this allows a domain named default.

Then there's a small script ~/.ssh/update-config that links one of the files based on the domain passed on the command line:

#!/bin/bash`

config=~/.ssh/config
default_config=${config}:default

domain="$1"
domain_config=${config}.${domain}

if test -f ${domain_config}; then
    echo "Using config ${domain_config}"
    ln -sf ${domain_config} ${config}
else
    echo "Using default config ${default_config}"
    ln -sf ${default_config} ${config}
fi

You can then call this script manually with appropriate domain as a first parameter.

To automate this thing I also added a NetworkManager hook (/etc/NetworkManager/dispatcher.d/02-sshconfig):

#!/bin/bash

case "$2" in
    up|dhcp4-change)
        break
        ;;
    *)
        exit 0
        ;;
esac

# some iface went up

for home in /home/*; do
        user=$(basename ${home})
        script="${home}/.ssh/update-config"
        test -x ${script} && su -l ${user} ${script} ${IP4_DOMAINS}
done

exit 0

Now, whenever an interface comes up or its DHCP configuration is changed this script runs update-config for each user.

Not ideal (what if wired network has different domain than wireless, no domain in DHCP configuration, etc.) but it had been working for me for years so well that I forgot I had it configured and I had to dig around my old laptop to transplant it to a new one.

If there is no domain provided by DHCP configuration you can try to base the config selection on something else, like your assigned IP.

There are of course some duplicates in the configs so maybe a one source config with special tags (DHCP domain, IP address/range) and a script that filters only tagged hosts to the actual configuration could be better. Maybe someone could get inspiration here.