102

I used ssh -L 10002:192.168.0.30:10002 192.168.1.135 to establish port forwarding but now I need to remove it.

How do I do this?

user16654
  • 1,273

7 Answers7

101

If you are using Linux you can kill the process by:

ps aux | grep ssh

and then use

kill <id>

To kill the process.

If the kill command is not successfull you can try

kill -9 <id>
Martin
  • 305
zpon
  • 1,274
73

When using ssh multiplexing,
killing the ssh process is often undesirable (it kills all open connections with that host),

and you cannot easily access the escape because "escape not available to multiplexed sessions".

The right way is then to run the analogue of the forwarding command that you want to cancel,
but adding -O cancel. For instance:

ssh -O cancel -L 10002:192.168.0.30:10002 192.168.1.135

This will disable this port forwarding without terminating the session.
Again, this will only work if ssh multiplexing is in use for the connection to 192.168.1.135.

yurenchen
  • 585
a3nm
  • 1,335
34

How to cancel a forwarded port in an already running SSH session:

  1. Press ~+C (tilde + capital C)
  2. Type -KL 10002 (or whatever port number)
  3. Press Enter

You should see this:

ssh> -KL 10002
Canceled forwarding.
19

You can enter an interactive console by typing ~C (capital "C"). This lets you dynamically add and remove port forwardings (among a few other things).

This sequence has to come right after a carriage return/newline. So in doubt, just type Enter~C (in sequence).

If you don't see the characters appear on the console, you're doing it right :)

You should now see an ssh> prompt.

To remove the port, simply enter -KL 10002 followed by Enter (where 10002 is your forwarded port).

The inverse - adding a new forward - can be done like this (from start to finish):

Enter~C

ssh> -L 10002:192.168.0.30:10002

Enter

exhuma
  • 1,247
13

You could use the "escape-key" (usually ~) followed by C to get a cli to your connection. You can from there remove tunnels without taking down your connection.

1

Pressing Ctrl+d will close it gracefully

Or you could just close the terminal

Jason
  • 11
0

killall ssh is also a neat variant which is easy to remeber and convenient if nothing except SSH port forwarding is enabled. Note it will stop all opened SSH connections also.