12

I use dynamic SSH port-forwarding (-D) and normal SSH port-forwarding (-L or -R) for many different things, including adding a layer of encryption to my wireless web traffic. The command I use normally looks something like this:

ssh -l raam -D 9000 my-linux-server.com

After starting the tunnel, I configure my web browser to use a SOCKS v5 Proxy of 127.0.0.1 with port 9000. Now all traffic in my browser (except DNS) is transmitted through the SSH tunnel.

When I'm ready to close the tunnel (when I'm taking my laptop to another location, for example), I simply type "logout". However, the SSH session hangs and I have to press CTRL+c to get my local prompt back.

Why does this happen and how can I prevent it?

(My guess is that the connections I opened through the tunnel remain open and my local SSH client is waiting for them to close before giving me my prompt back. If this is the case, how can I force all those connections to close when I'm ready to logout?)

chicks
  • 3,793
  • 10
  • 27
  • 36
Raam Dev
  • 143
  • 1
  • 7

4 Answers4

22

As you expected, this happens because SSH won't exit if there are outstanding connections going through the tunnel.

If you exit your browser (and all other programs that are going through the port 9000 tunnel) then SSH should exit.

The SSH man page says:

The session terminates when the command or shell on the remote machine exits and all X11 and TCP connections have been closed.

And I don't see any options to change that behavior, so I suspect there's nothing you can do.

Matthias Braun
  • 225
  • 1
  • 8
slacy
  • 930
  • 1
  • 9
  • 11
7

You can background SSH doing:

<enter>~&
Juliano
  • 5,512
  • 28
  • 28
  • 1
    or even better, use ssh -f – Thomas Jun 05 '09 at 18:38
  • @Thomas That won't work since the ssh connection is being used interactively until loging out. But in some cases it may be useful to keep port forwardings and interactive usage on separate ssh connections. – kasperd Sep 06 '15 at 14:18
4

As stated in the comment you can create a tunnel only connection using -f, but you'll still have the issue of the connection not terminating until everything using the tunnel has exited. You can use the ~# option (escape sequence and a 'pound') to list the forwarded connections you have open on a given connection before you logout.

Stick
  • 658
  • 4
  • 10
1

Instead of typing exit which closes your shell but leaves the session open until the tunnels are disconnected from, you can actually ask your shell to close the session directly which kills the tunnels and shell.

kill $PPID

Your interactive shell's parent process is the sshd process handling your session.

This also works with commands so they wont hang;

ssh -R 9000:localhost:9000 my-linux-server.com './scriptThatUsesRemotePort.sh; kill $PPID'

If you don't have $PPID environment variable you can use kill `ps --no-headers -eo ppid -fp $$`

Hashbrown
  • 313
  • 2
  • 4