216

So I typically run this command a lot:

ssh -L 5901:myUser@computer.myHost.edu:5901

I use it to do VNC over SSH.

How do I convert that command into something that will work in a ~/.ssh/config file?

ex:

host yam
    HostName yam.myHost.edu
    User myUserName

all I want to do is type:

ssh yam

And have it open a SSH shell with a local listen port, and a remote port forwarded to it.

Suggestions?

Snow_Mac
  • 5,727
  • 17
  • 54
  • 80
  • 3
    Why was this not migrated to SuperUser? – johnsyweb Feb 05 '12 at 20:59
  • @Johnsyweb We don't insta-migrate unless we are *sure* that it would make for good content on the target site (which a number of factors play into). However, if it is decidedly *off topic* for this site, it's closed as such on the spot. – casperOne Feb 05 '12 at 21:34
  • 10
    @casperOne: Six years later, it seems that the community find this question and its accepted answer to be helpful. Is there a way to migrate it to SuperUser? – johnsyweb May 01 '18 at 08:54

1 Answers1

329

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • 25
    Thanks. This works too: `LocalForward 5901 localhost:5901`. Putting port forwarding in config files is probably the best way to forward multiple ports. – Philip Kearns Feb 22 '17 at 15:30
  • 5
    For me, only `LocalForward port localhost:port` worked. Any reason for the other to not work? – Priyath Gregory Oct 05 '17 at 10:17
  • @fsociety: I recommend asking a fresh question on superuser.com explaining *how* it "doesn't work". – johnsyweb Oct 05 '17 at 22:11
  • 1
    Ran into something like this today, multiple `LocalForward` statements works great for repetitive forwarding of multiple distinct ports (OpenSSH 7.1) – deaks Feb 02 '18 at 04:38
  • 1
    @fsociety: it depends on the machine that has the open port you want to forward. These are two different scenarios. If you want to forward a port directly on the host of your SSH connection, use `localhost`. – blissini Oct 24 '18 at 15:40
  • 31
    That feeling when you are trying to set up multiple port forwarding and searching the web leads you to something you knew seven years ago but somehow forgot… – johnsyweb Apr 15 '19 at 12:02
  • 1
    ~/.ssh/config FTW – deepelement Sep 26 '19 at 21:18
  • 1
    If you have two terminal windows that you are connecting from to the same host or multiple host entries that specify local port one of them will fail. So (1) its a good idea to use unique local port numbers per host, and (2) if you also add ControlMaster (with relevant supporting configs) the forwarding would be on the first connection and you will not get an error and the forwarding will survive user existing the first. – nhed Feb 17 '22 at 23:13