I am using the program synergy together with an ssh tunnel
It works, i just have to open an console an type these two commands:
ssh -f -N -L localhos
There are many interesting answers here, but nobody mentioned that the manpage of SSH does describe this exact case! (see TCP FORWARDING section). And the solution they offer is much simpler:
ssh -fL 12345:localhost:12345 user@remoteserver sleep 10
synergyc localhost
Now in details:
-f it will initiate the connection and only then fork to background (unlike solutions with ssh ... &; pid=$! where ssh is sent to background and next command is executed before the tunnel is created). On the remote machine it will run sleep 10 which will wait 10 seconds and then end.synergyc localhost. It will connect to the tunnel and SSH will then know that the tunnel is in use.sleep 10 command will finish. But the tunnel is still in use by synergyc, so SSH will not close the connection connection until the tunnel is released (i.e. until synergyc closes socket).synergyc is closed, it will release the tunnel, and SSH in turn will terminate itself, closing a connection.The only downside of this approach is that if the program we use will close and re-open connection for some reason then SSH will close the tunnel right after connection is closed, and the program won't be able to reconnect. If this is an issue then you should use an approach described in @doak's answer which uses control socket to properly terminate SSH connection and uses -f to make sure tunnel is created when SSH forks to the background.