when I am connected to a device over SSH, I know how to forward local ports; first enter ssh menu with [ENTER} ~C, then: -L 4455:ip:80

This will make localhost:4455 on my local machine go to port 80 on the remote device.

How can I instead put this manual action into a script? The only variable here is the IP address on the remote device, but I know how to get that automatically; I just don't know how to push commands to the ssh menu, such as: -L 4455:ip:80.

  • Why even use the menu? You can pass all of this directly on the command line. – Panki Jan 7 '19 at 15:21
  • @Panki sorry for the weird question, but how? i still have lots to learn about linux, but i'e always used the ssh menu to forward ports when connected over ssh, the code 'ssh -L 4455:ip:80' does not work nor does 'ssh -N -L 4455:ip:80' – WingZero Jan 7 '19 at 15:56


I recently ran into this post: https://hackertarget.com/ssh-examples-tunnels/ It explains a lot about ssh connections and port forwarding, have a look, you will learn a lot :)

Here is the bit that is relevant to you:

SSH Tunnel (port forward)

In its simplest form an SSH tunnel simply opens a port on your local system that connects through to another port at the other end of the tunnel.

localhost:~$ ssh -L 9999: user@remoteserver

Lets break down the -L parameter. Think of -L as the Local listening side. So in our example above the port 9999 is listening on localhost and port forwards through to port 80 on remoteserver, note that the refers to localhost on the remote server!

Lets take it up a notch. In this following example the port that is listening can be connected to from other hosts on the local network.

localhost:~$ ssh -L user@remoteserver

In these examples the port we are connecting is a listening web server. It could also be a proxy server or any other TCP service.


Now, the above will open an active SSH shell for you, and, as we only want to forward the port this is unwanted. You can add the -N argument to the command to skip executing any remote commands (the opened shell is a command too). The ssh man page explains this as well:

-N Do not execute a remote command. This is useful for just forwarding ports.

So, the following script will open your port until you ctrl-c/kill it:

#!/usr/bin/env sh

echo "Forwarding ports"
ssh -N -L user@remoteserver

You can also open a port for a few seconds by executing a sleep command and removing the -N argument:

ssh -L user@remoteserver "sleep 10"


These SSH tunnels have their pitfalls. If you want to keep the forwarded port open for a long time, you might want to check out the following thread, specifically the bit about autossh: https://superuser.com/questions/37738/how-to-reliably-keep-an-ssh-tunnel-open

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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