Consider the following command (which is part of a script I'm writing):

ssh -oClearAllForwardings=yes -NL 5555:localhost:5555 foo

I want ClearAllForwardings=yes because I might have LocalForward options in my ssh config and I don't want these to happen within this command (if they're already being forwarded elsewhere and it'll warn about port in use which is confusing when running this script).

But it seems that ClearAllForwardings=yes causes ssh to completely ignore ALL forwards, even when given later on the command line.

I can't tell ssh to completely ignore ~/.ssh/config because that contains the information about how to reach foo.

So how can I get ssh to ignore LocalForward from ~/.ssh/config but still allow forwarding a specific port on the command line?

1 Answer 1


~/.ssh/config is your private file, under your control. Use this fact and arrange the file like this:

Host foo bar
   Hostname …
   # common options here

Host foo
   # forwardings here

ssh foo will match both sections. Your script shall ssh -L … bar; this command will match the section with common options, but it will not match the section with forwardings.

Note you need Hostname. If your previous config did not specify one for foo, the implicit hostname for ssh foo was foo and now you need Hostname foo (so ssh bar connects to foo, not to bar).

If for any reason you don't want to edit ~/.ssh/config (e.g. you want a solution that is fully "inside" the script), consider the following:

Your script can run ssh -oClearAllForwardings=yes -fNMS … foo and then it can add/remove port forwardings by communicating with the master ssh process by invoking ssh -S … -O …. See this other answer of mine for an example that adds remote forwarding (-R); adding local forwarding is similar, you will need like ssh -S … -O forward -L 5555:localhost:5555 placeholder.

  • Amazing! ...never knew you could do this.
    – Seamus
    Dec 4, 2023 at 17:02
  • Changing ssh config isn't an option here. Adding the forwarding later using controlmaster is interesting. Is placeholder completely ignored or could you accidentally still end up with extra forwards if you put the real hostname here? Dec 5, 2023 at 18:21
  • 1
    @SystemParadox AFAIK with -S and without -M, and with sane -O the destination is irrelevant, yet the argument has to be there. Dec 5, 2023 at 18:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .