Bash: SSH: Checking if an IP or host with non standard port is in known_hosts

589 views Asked by At

I'm trying to test if a SSH host has been connected to before in a bash script. It uses a non-standard port.

I'm using a test as suggested from this question/answer, and I know for certain the SSH host in this test is in known_hosts, but the test does not seem to work as expected.

Is it not possible to test for IP addresses using ssh-keygen -F? Or is this an issue with using non-standard ports (as a check for some.host.com:4567 doesn't work here either)...

#!/bin/bash

# test for IP address
if ssh-keygen -F '192.168.1.10:1234'; then
    echo "Yes, a known host."
fi

## Expected Output:
#
## Host 192.168.1.10 found: line 6
#|1|hashblahblahblah
#Yes, a known host.
#
## Actual Output:
#

Any ideas?

1

There are 1 answers

3
John1024 On BEST ANSWER

ssh-keygen expects square-brackets around the host/IP. Thus, replace:

ssh-keygen -F '192.168.1.10:1234'

with:

ssh-keygen -F '[192.168.1.10]:1234'

You can check this by looking at ~/.ssh/known_hosts. The first item, after "markers" if any, on each line is a comma-separated list of hosts (with ports if nonstandard). ssh-keygen -F seems to expect the same format on the command-line as is used in the file.