How to make ssh match known_hosts to host/ip:port instead of just host/ip?

Solution 1:

The version of OpenSSH that comes with CentOS 5 does not support port numbers in known_hosts. You will need to build and install a newer version if you want this to work.

Solution 2:

~/.ssh/config:

Host foohost-2201
    Hostname foohost.domain.tld
    # This should comply with the format used in OpenSSH 5.
    HostkeyAlias "[foohost.domain.tld]:2201"
    User username
    Port 2201

And seriously, upgrade.

Solution 3:

Use this if your openssh client does not support host+port based entries:

The directive 'GlobalKnownHostsFile' can be misused to point to a different file for each of your 2 firewalled machines (here Alice and Bob). However these two files have to be prepared with correct host keys of either alice or bob in advance as they are not written to when accepting unknown keys.

It's not really fun to set up but once it's done it works.

My previous workaround before this was 'StrictHostKeyChecking no' which does not allow ssh-agent to forward keys nor to have ports forwarded (blocked by openssh when used).

My .ssh/config looked like this until recently:

Host hoppingstation
        Hostname loginhost.somewhere.net
        User me
        LocalForward 2201 alice.somewhere.net:22
        LocalForward 2202 bob.somewhere.net:22
Host alice
        Hostname localhost
        Port 2201
        User root
        ForwardAgent yes
        GlobalKnownHostsFile /home/me/.ssh/known_hosts_alice
Host bob
        Hostname localhost
        Port 2202
        User root
        ForwardAgent yes
        GlobalKnownHostsFile /home/me/.ssh/known_hosts_bob