Script to establish SSH tunnel and then run another program that uses the tunnel

10,033

Use ssh -fNT -L 5433:127.0.0.1:19097 [email protected] to ask ssh to automatically background after establishing the tunnel, and then your script can move on the next command. I suggest you end the script with an exit, which will close the terminal and kill the ssh process; otherwise you must either explicitly kill it or it will exit if/when the server times it out.

Share:
10,033

Related videos on Youtube

saran kumar
Author by

saran kumar

Updated on September 18, 2022

Comments

  • saran kumar
    saran kumar almost 2 years

    I am running a GUI app (Gnucash) that connects to a remote Postgres database via a secure shell session. I can use the SSH -L command to tunnel a local port and then separately run Gnucash and this works fine.

    What I'd like to do is use a single shell script that sets up the tunnel and then calls Gnucash. Is that possible? If so, how do I do it? Currently, I run commands like the following in 2 separate terminal windows:

    ssh -L 5433:127.0.0.1:19097 [email protected] gnucash postgres://gnucash@localhost:5433/gnucash_db

    If I simply put both lines in a shell script, the first line drops me into the remote shell and the second line doesn't execute until I exit the remote shell.

    TIA, Rob Hills

    • Ian B.
      Ian B. almost 12 years
      How about adding a & to the end of the first line? Would that help?
    • saran kumar
      saran kumar almost 12 years
      I've not yet tried that, partly because I've been distracted by another task and partly because of the belief that using the & at the end would leave the tunnel process in the background, leaving the connection open. Not sure if it would close when I finished the script or if it would stay open until I shut down Ubuntu. I'll have to test this when I get a chance.
  • Steve Kroon
    Steve Kroon almost 12 years
    He wants to run gnucash on the remote server, so presumably he doesn't want -N. Not sure how the -T interacts either, but the -f should do the trick.
  • Matthew Flaschen
    Matthew Flaschen over 11 years
    This does not kill the ssh process, even with the explicit exit (which has no effect, since the script is would exit at the end of code anyway).