14

I need to add a check if the hostname is already present in the known_hosts file.

Normally I would do something like that:

ssh-keygen -H -F hostname

However, that does not seem to work for me in this particular case. I connect to the host using port 2102, like that:

ssh user@myhost -p 2102

I was asked to add the hostname to the known_hosts file, I say yes. After that I run ssh-keygen -H -F myhost but receive empty result.

To make the matter worse, the known_hosts is hashed.

That works perfectly with port 22, so if I login to ssh user@myotherhost, save the known host and run ssh-keygen -H -F myotherhost I receive the exact line from the file.

So, how can I adjust the command to work with port 2102?

AdminBee
  • 21,637
  • 21
  • 47
  • 71
deimos
  • 673
  • 5
  • 14

1 Answers1

17

You can use this format: [hostname]:2121, as it is stored in the known_hosts file (note, you need to use the square brackets!):

ssh-keygen -H -F "[hostname]:2121"

Proof of concept (transcript of my minimal test case):

$ echo "[hostname]:2121 ssh-rsa AAA...==" > known_hosts
$ ssh-keygen -Hf known_hosts 
known_hosts updated.
Original contents retained as known_hosts.old
WARNING: known_hosts.old contains unhashed entries
Delete this file to ensure privacy of hostnames
$ ssh-keygen -H -F "[hostname]:2121" -f known_hosts
|1|R21497dX9jN052A92GSoVFbuTPM=|lRtIr6O564EaFG0SsIulNAWpcrM= ssh-rsa AAA...==

You might need to use IP address instead of hostname, but it should generally work.

Michael Mrozek
  • 91,316
  • 38
  • 238
  • 232
Jakuje
  • 20,974
  • 7
  • 51
  • 70