I've got some remotely managed devices as per this description, such that to connect from my server I type:

ssh localhost -p 2870

Since I've got a bunch of hosts I'm managing, I wanted to shortcut this so I could just type:

ssh 2870

I don't want to use bash aliases (since then I couldn't also use SCP and Ansible), so tried this in ~/.ssh/config:

Host 28??
       HostName localhost
       Port %h

This fails since for whatever reason %h doesn't expand on the Port line (it will on HostName and others). So tried this instead:

Host 28??
       ProxyCommand ssh -v localhost -p %h

Here %h expands OK, and I can see it logs into the server OK (via publickey) but I don't receive a prompt.

Any ideas on how I could do this 'aliasing' in ssh config?

  • You can shorten that even more by using an alias: alias s='ssh localhost -p'. Then type s 2870.
    – ott--
    Sep 20 '16 at 18:45

It seems as though the %h expansion just doesn't work in the Port directive. If you don't mind filling up .ssh/config with a lot of entries, it's not hard to generate them dynamically (especially if you have a list, or they're sequential):

$(for port in `seq 2000 2900`
   echo Host $port
   echo "  Hostname localhost"
   echo "  Port ${port}"
   echo ""
 done) >> ~/.ssh/config

Since we can look at the source code for ssh, it's possible to confirm that expansion is not performed for Port:

readconf.c: https://github.com/openssh/openssh-portable/blob/dc664d1bd0fc91b24406a3e9575b81c285b8342b/readconf.c

Calls a function percent_expand for host and exec options - that appears to be the function that converts %h into a hostname. The same function is called from ssh.c. Interestingly, it looks like ProxyCommand defers expanding those variables until later. It is not called for the Port directive.


  • Thanks Ian. I did end up adding a bunch of entries, pretty much as you've demonstrated. But I'm still hoping there's a nicer way to achieve it. Appreciate the link to the source code, that explains why the expansion didn't work as expected.
    – gaddman
    Sep 15 '16 at 20:15

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.