I want to run a command that needs a SSH tunnel for its operation (opening TCP connections repeatedly). After it exists, the tunnel needs to be closed again. The problems I encountered are:
I can run the command in the background immediately, but then I have no reliable way how to be sure the tunnel has been set up:
#!/bin/bash set -e ssh -N -L lport:server:port host & trap "kill $!" EXIT sleep 1 my program that connects to localhost:lport
It often happens that opening the tunnel takes longer than 1s. I could also put there more time, but then the user experience isn't very good, and still it's unreliable.
I can let SSH background itself when the connection is opened, but then I can't find a reliable way how to kill it afterwards, because I don't know the PID of the background SSH process:
#!/bin/bash set -e ssh -f -N -L lport:server:port host # I'd set up a trap ??? EXIT, but for what? my program that connects to localhost:lport
Is there a way how to detect the PID of the SSH process?
Or is there another, better way how to solve the task?