Network-dependent ~/.ssh/config?

Solution 1:

Depending on how your proxy is configured, you can simply build an SSH config entry that works in either situation. For example on one network I regularly use I have to ssh to an intermediate host before I can make an outbound connection. So basically I setup a configuration that looks like this.

# proxy ssh 
Host *%sshproxy
    ProxyCommand ssh [email protected] /bin/netcat -w 1 $(echo %h | cut -d%% -f1) 22

Host myhost.example.org
    HostName 172.16.24.1

Host otherhost.example.com
    HostName 192.168.57.12

So when I don't need to use a proxy, I can simply run a command like ssh myhost.example.org and get connected, but when I do need the proxy, I run the command ssh myhost.example.org%sshproxy.

I suspect you could probably setup some kind of alias or auto-complete setting that would automatically append the %proxy bit.

Solution 2:

Old question, but some ideas in this thread helped me and this is a solution I came up with:

First, the proxy server ssh configuration.

Match Originalhost proxy Exec "ifconfig | grep 10.0.1"
     Hostname 10.0.1.2
Host proxy 
     Hostname external.hostname.com

Then, the Server B configuration:

Match Originalhost server-b Exec "ifconfig | grep 10.0.1"
     ProxyCommand none
Host server-b
     Hostname 10.0.1.3
     ProxyCommand ssh -W %h:%p server-a

The idea here is that the default case is connecting from an external site and the ProxyCommand initiates an ssh connection to proxy first and then connect to server-b. If, on the other hand, we are located on the local subnet already, the ProxyCommand is disabled and no proxy connection to server-a is made.

Regardless of where you are, you can always reach server-abc by this entry and this setup figures out where you are and sets up the connection accordingly. For server-xyz, just use the same idea.

I made a more thorough explanation here: http://blog.kihltech.com/2017/04/ssh-conditional-host-address-based-on-network-or-location/