2

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?

nooblag
  • 678
  • 3
  • 23

1 Answers1

4

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.

John1024
  • 109,961
  • 14
  • 137
  • 171
  • Quick follow-up. I was not able to get this working with variables. For example, this code returns empty: `ssh-keygen -F '[${remoteHost}]:${remotePort}'` with `remoteHost="192.168.1.10"` and `remotePort="1234"`. Any ideas? – nooblag Aug 28 '20 at 18:43
  • 1
    @nooblag Shell variables do _not_ expand inside single-quotes. Use double-quotes: `ssh-keygen -F "[${remoteHost}]:${remotePort}"` – John1024 Aug 28 '20 at 19:29
  • 1
    Ahhh, great! Thanks @John1024! – nooblag Aug 28 '20 at 20:01