0

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:

  1. 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.

  2. 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?

  • You might be able to use ssh -o LocalCommand=yourprogram to launch the progam once the connection has been established (you might also need to set PermitLocalCommand=yes). However, as per man ssh_config: "It should not be used for interactive commands." – n.st Jan 9 '14 at 23:13
0

See https://stackoverflow.com/questions/2241063/bash-script-to-setup-a-temporary-ssh-tunnel for answers containing Control Socket and ExitOnForwardFailure.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.