0

I have a script that needs a tunnel to a remote server. Something like this:

ssh -fNL 8080:localhost:80 my_server

How can I close the tunnel after my local script ends?

The above example is just one of the combinations I tried. I have seen how to make a blocking ssh call, executing a remote command and a self closing the tunnel with 'sleep', but I just want a way to provide the tunnel only during the execution of my script.

My last approach was forking ssh into the background and let it get killed when the script dies, but with the above command the ssh process is still alive after ending the script. Also I am exploring how to obtain the PID to manually kill the background ssh.

1

Just use

function atexit() {
  kill $TUNNEL_PID
}
trap atexit EXIT
ssh -nNL 8080:localhost:80 my_server &
TUNNEL_PID=$!

(ie, don't tell ssh to background itself, just run it as a regular background task and save the pid)

0

You should be able to background your ssh command by adding & at the end. Then, on the very next line, add

SSHPID=$!

$! is the PID of the most recent background command, so it's the PID of your SSH session. Then, at the end of your script, just kill -SIGKILL $SSHPID.

0

Just tested a solution, I dislike how it's done, but it works :

Pre-requisites :

  • screen command installed
  • ssh connection using allready unlocked ssh key

Explanation on how to build the solution :

add to following line where you need to start your tunnel :

screen -d -m -S myTunnel ssh 0.0.0.0:123:118.218.118.218:5555 myServer # starts a screen in detached mode and create your tunnel

Run your actions and add this to the end of you script :

kill `ps -A -o -pid,cmd|grep "SCREEN -d -m -S myTunnel"| grep -v grep| head -n 1| awk '{print $1}'` # kills the opened screen
screen -wipe  # clears screens list (not allways usefull, depends on the commands ran by the screen)

Tunnel is now down.

This solution works (just tested it) but this is not a state of the art answer.

Thanks to chepner's answer I allways use when needed

EDIT : I was sure there will be better answers

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