Connect SSH hostname with different address

Published on
2 mins read

Untitled.png

When I am at home, I would like to connect to my server via internal local address. But when I am working outside, I would like to connect to my server via VPN address.

Usually this can be done with 2 different hostname in .ssh/config like this.

ssh server
  HostName 198.11.1.2

ssh server-remote
  HostName 100.2.14.6

But this will be a very big problem when you have multiple config in these 2 instances

ssh server
  HostName 198.11.1.2
	Port 34889
  # Expose for Apple's built-in VNC service
  LocalForward 5900 localhost:5900
  # Expose SOCKS5 proxy for browser to have access to VPN
  DynamicForward 6789

ssh server-remote
  HostName 100.2.14.6
	Port 34889
  # Expose for Apple's built-in VNC service
  LocalForward 5900 localhost:5900
  # Expose SOCKS5 proxy for browser to have access to VPN
  DynamicForward 6789

Introducing Match directive

With Match exec property of sshd_config, you can execute custom command in ssh config. Configuration will be applied when command exit with code 0

With this knowledge, you can combine all configuration into just one host.

ssh server
	Port 34889
  # Expose for Apple's built-in VNC service
  LocalForward 5900 localhost:5900
  # Expose SOCKS5 proxy for browser to have access to VPN
  DynamicForward 6789

Match exec "ifconfig | grep 'inet 198.11.1'" Host server
  HostName 198.11.1.2

Host server
	HostName 100.2.14.6