Bash script to set up a temporary SSH tunnel

前端 未结 6 1007
你的背包
你的背包 2020-12-12 08:46

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 shut down the
相关标签:
6条回答
  • 2020-12-12 09:26

    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.

    0 讨论(0)
  • 2020-12-12 09:30

    You can tell SSH to background itself with the -f option but you won't get the PID with $!. Also instead of having your script sleep an arbitrary amount of time before you use the tunnel, you can use -o ExitOnForwardFailure=yes with -f and SSH will wait for all remote port forwards to be successfully established before placing itself in the background. You can grep the output of ps to get the PID. For example you can use

    ...
    ssh -Cfo ExitOnForwardFailure=yes -NL 9999:localhost:5900 $REMOTE_HOST
    PID=$(pgrep -f 'NL 9999:')
    [ "$PID" ] || exit 1
    ...
    

    and be pretty sure you're getting the desired PID

    0 讨论(0)
  • 2020-12-12 09:32
    • 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 flag (I see you already did this with -N).
    • Save the PID with PID=$!
    • Do your stuff
    • kill $PID

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

    0 讨论(0)
  • 2020-12-12 09:40

    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

    0 讨论(0)
  • 2020-12-12 09:43

    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
    
    0 讨论(0)
  • 2020-12-12 09:45

    You can do this cleanly with an ssh 'control socket'. To talk to an already-running SSH process and get it's pid, kill it etc. Use the 'control socket' (-M for master and -S for socket) as follows:

    $ ssh -M -S my-ctrl-socket -fnNT -L 50000:localhost:3306 jm@sampledomain.com
    $ ssh -S my-ctrl-socket -O check jm@sampledomain.com
    Master running (pid=3517) 
    $ ssh -S my-ctrl-socket -O exit jm@sampledomain.com
    Exit request sent. 
    

    Note that my-ctrl-socket will be an actual file that is created.

    I got this info from a very RTFM reply on the OpenSSH mailing list.

    0 讨论(0)
提交回复
热议问题