tags:

views:

571

answers:

4

On CYGWIN, I want a BASH script to:

  1. create an SSH tunnel to a remote server.
  2. Do some work locally that uses the tunnel.
  3. Then shutdown the tunnel.

The "shutdown part" has me perplexed.

Currently, I have a lame solution. In one shell I run the following to create a tunnel.

# Create the tunnel - this works! It runs forever, until shell is quit.
ssh -nNT -L 50000:localhost:3306 [email protected]

Then, in another shell window, I do my work

# Do some MYSQL stuff over local port 50000 (which goes to remote port 3306)

Finally, when I am done. I close the first shell window to kill the tunnel.

I'd like to do this all in one script like: # Create tunnel # do work # Kill tunnel

How do I keep track of the tunnel process, so I know which one to kill?

+2  A: 

You could launch the ssh with a & a the end, to put it in the background and grab its id when doing. Then you just have to do a kill of that id when you're done.

Valentin Rocher
+3  A: 
  • You can tell ssh to go into background with & and not create a shell on the other side (just open the tunnel) with a command line flage (I see you already did this with -N).
  • Save the PID with PID=$!
  • Do your stuff
  • kill $PID

EDIT: Fixed $? to $! and added the &

ZeissS
$?? No, $!! . .
mobrule
If my script dies somewhere before it gets to the KILL, I have to be careful to handle that.
jm
@mobrule: your right. fixed.
ZeissS
@jm: `trap 'kill $PID' 1 2 15` will cover many cases of script failure.
Norman Ramsey
For this to work reliably, i had to "sleep" a little AFTER creating the tunnel, but before using it.
jm
+3  A: 

I prefer to launch a new shell for separate tasks and I often use the following command combination:

  $ sudo bash; exit

or sometimes:

  $ : > sensitive-temporary-data.txt; bash; rm -f sensitive-temporary-data.txt; exit

These commands create a nested shell where I can do all my work; when I'm finished I hit CTRL-D and the parent shell cleans up and exits as well. You could easily throw bash; into your ssh tunnel script just before the kill part so that when you log out of the nested shell your tunnel will be closed:

#!/bin/bash
ssh -nNT ... &
PID=$!
bash
kill $PID
too much php
Very interesting. This may handle the "trap" problem better. Will have to try it.
jm
A: 

Another potential option -- if you can install the expect package, you should be able to script the whole thing. Some good examples here: http://en.wikipedia.org/wiki/Expect

Phil Pelanne