The below solution was tested with ssh from OpenSSH, version 9.3 (but it should work with reasonably non-ancient older versions as well, I guess from 7.2 where bz#2471 was fixed). For 9.4 and later see this other answer, IMO the solution there is The Right Thing.
Paste this snippet at the beginning of your ~/.ssh/config:
Match exec "case $VNCT in ?) exit 0;; esac; exit 1" LocalForward 5900 localhost:5900Now if you run ssh with non-empty VNCT in the environment then LocalForward 5900 localhost:5900 will be applied. Like this:
VNCT=1 ssh -N MyHostNameThe solution can be expanded. E.g. this additional snippet:
Match exec "case $PRXY in ?) exit 0;; esac; exit 1" LocalForward 8080 localhost:8080will allow you to run VNCT=1 PRXY=1 ssh -N MyHostName to enable both forwardings. You can enable each forwarding independently. You can create more snippets.
Notes:
case $VNCT in ?) exit 0;; esac; exit 1is not the simplest way to test if the variable is not empty. In general there are simpler ways, but many of them require double-quoting in the shell code. I haven't found a way to pass"inside the double-quoted value toMatch exec, therefore I decided to usecasewhere double-quoting is not necessary.It's about non-empty variable vs empty/unset, so
VNCT=0will also enable the respective forwarding. If you usecase $VNCT in 1) …then onlyVNCT=1will enable it, every other value (includingVNCT=0) will not.The solution may even work with scripts and tools that use
sshunder the hood; or in some cases it may not.A tool may run
sshin a sanitized environment or with options that interfere, but if it callssshin the most straightforward way then our config will work, you just need to put the right variable into the environment (e.g.VNCT=1 tool). I don't expect you'd want to create tunnels this way, but you are not limited toLocalForward, with our method you can impose other configuration options on demand. This will be particularly useful if the tool does not provide any option to customize arguments it passes tossh.