Ssh – Use two different ip addresses per host in SSH

opensshssh

I have a server, named gamma, constantly up and running at work. Sometimes I connect to it from at home, in which case I use the public IP address 55.22.33.99. Sometimes, I connect to it when I'm at work, and rather than bounce my packets around unnecessarily, I connect via the local IP address, 192.168.1.100.

At the moment, I have them split up into two different entries in ~/.ssh/conf

Host gamma-local
        HostName 192.168.1.100
        Port 22
        User andreas

Host gamma-remote
        HostName 55.22.33.99
        Port 12345
        User andreas

So, if I'm at work, all I have to type is ssh gamma-local and I'm in; if I'm at home (or anywhere else in the world), I run ssh gamma-remote.

When connecting to the server, I would rather not have to type in a different name depending on where I am, I would rather that part be done automatically; for instance, in some cases I have automated scripts that connect who don't know where I am.

There is a question that solves this problem by using a Bash script to "try" to connect to the local one first, and if it doesn't connect, try to connect to the remote IP address. This is nice, but (1) seems inefficient (especially since sometimes you have to "wait" for connections to time out as they don't always send an error back immediately) and (2) requires Bash and lugging around the script.

Is there an alternate way of achieving this that doesn't rely on the use of Bash scripts, nor "testing" to see if the connection works first?

Best Answer

If you have a way to recognize which network are you on then you can use the Match keyword in ~/.ssh/config to do what you want. This requires OpenSSH ≥6.5.

I use something similar to

Match originalhost gamma exec "[ x$(/sbin/iwgetid --scheme) != xMyHomeESSID ]"
  HostName 192.168.1.100
  Port 22

Host gamma
  User andreas
  Port 12345
  HostName 55.22.33.99

So I'm using the identifier of the used wifi network to decide whether I'm at home for the purposes of the SSH connection, but checking the IP address assigned to you computer or anything else that differentiates the two networks can be used as well.

Related Question