21

I'm using openssh on both client and server. I know I can run ssh -L or ssh -R to setup some port redirections over ssh. However, since they are command-line parameters, such redirections must be written before the connection is opened.

Can I setup port redirections on-the-fly using the command-line ssh client?

When I used the PuTTY ssh client, I could interactively setup a port redirection while a connection was already opened, without dropping nor reconnecting, thus I know it is technically possible.

Denilson Sá Maia
  • 1,707
  • 2
  • 13
  • 14

1 Answers1

34

If you're using the SSH command line, and you haven't switched the escape character feature off, then you can type ~C after a newline to open a mini-console on the ssh client. Then type -L port:host:port or -R port:host:port or -D port as you would on the command line to add a redirection, or -KR port to remove a redirection.

A more flexible method to set up redirections without redoing the authentication is to start the first ssh client as a master (-M or -o ControlMaster=auto) and subsequent clients as slaves (-S or -o ControlMaster=auto). The slaves tunnel through the connection established by the master. You may need to set ControlPath on the command line or in your ~/.ssh/config; see the description of the options in the ssh_config man page for more information.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
  • 1
    In case anyone runs into the `~C escape not available to multiplexex sessions` problem as I did just now, don't go hunting for your master connection. Instead, just add `-O forward` to your ssh port forwarding command, as in `ssh -O forward -nfL 1234:whatever:1234 theserver` and it'll work. – Patrick Oct 19 '16 at 11:33
  • Note that Enter must be pressed prior to the escape sequence. The Enter key gets forwarded to the host, so don’t do it with a half-entered command in limbo. On the other hand, if you have just launched a command by pressing Enter, you can proceed straight to the `~C` sequence. – user149408 Apr 05 '22 at 13:20