2

I have a proxy server which I connect to like so

ssh -L 2001:localhost:8888 -N myserver.com -p 443  

I then open up Firefox

firefox -p "SSHProxy"

(It starts Firefox configured to use port 2001). I browse a bit, then close Firefox and then stop the tunnel.

What I would like to do is automate it: open the tunnel, then open Firefox. When I close Firefox, I'd like to close the tunnel too.

Is this possible in a simple script?

I have tried

ssh -L 2001:localhost:8888 -N myserver.com -p 443 && firefox -p "SSHProxy"

but only the SSH bit executes, Firefox does not open. If I reverse the order, then SSH only opens after I close Firefox.


With help below I have used this simplified script:

#!/bin/bash -e

#Start SSH
ssh -L 2001:localhost:8888 -Nf myserver.com -p 443 &

#Start Firefox
firefox -p "SSHProxy" &

#Kill the SSH port 2001 when Firefox stops
trap "ps aux | grep ssh | grep 2001 | awk '{print \$2}' | xargs kill" EXIT SIGINT SIGTERM

wait

1 Answer 1

1

What about creating a bash script that uses arrays to store the PID and then trap and kill them:

#!/bin/bash -e

ssh -L 2001:localhost:8888 -N myserver.com -p 443 &
PID[0]=$!
firefox -p "SSHProxy" &
PID[1]=$!
trap "kill ${PID[*]}" INT SIGINT        
wait

If you need to use a password look here for sshpass: https://stackoverflow.com/questions/16937104/provide-password-to-ssh-command-inside-bash-script-without-the-usage-of-public

EDIT:

Run the script in terminal. Browse. When done browsing, go back to terminal and press Ctr-C (INT/SIGINT) the processes should be cleaned up. It seemed to work for me.

3
  • This looks promising - but the SSH connection doesn't die when I close Firefox, just stays open. I guess the trap isn't catching Firefox's exit? I've not heard of trap before but I read a bit and tried adding even more signals trap "kill ${PID[*]}" EXIT QUIT INT STOP TERM ERR SIGINT SIGTERM but it still wasn't caught.
    – Mendhak
    Feb 5, 2014 at 0:22
  • Got it - I needed to detect the PID of the SSH process differently, the PID[0] being reported in the script is wrong. So I did this: trap "ps aux | grep ssh | grep 2001 | awk '{print \$2}' | xargs kill" EXIT SIGINT SIGTERM If you modify your post I can mark yours as answer, thanks!
    – Mendhak
    Feb 5, 2014 at 0:51
  • @Shah I am glad that you got it working. Edited the answer, but it seemed to work for me with some minor adjustments.
    – jmunsch
    Feb 5, 2014 at 2:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .