How can I easily create entries in this hashed format?
You don't say how exactly you are currently adding the key to the known hosts file, but I am going to assume that you are using ssh-keyscan
, since that is the tool which is specifically designed for this exact use case:
ssh-keyscan
is a utility for gathering the public SSH host keys of a number of hosts. It was designed to aid in building and verifying ssh_known_hosts files, the format of which is documented in sshd(8). ssh-keyscan
provides a minimal interface suitable for use by shell and perl scripts.
So, I assume your script currently contains a line like this:
# Delete the entry for the old IP
ssh-keygen -R $OLD_IP
# Add entry for the new IP
ssh-keyscan $NEW_IP >> ~/.ssh/known_hosts
All you need to do is the add the -H
flag to generate the output in the hashed format:
ssh-keyscan -H $NEW_IP >> ~/.ssh/known_hosts
(I want to write a script to tell ssh that any ip in the 10.0.0.0/24 range is should match the given fingerprint.)
I believe that could be achieved in a much simpler way.
SSH has a KnownHostsCommand
configuration parameter which allows you to specify a command that outputs host key lines in the same format as the known hosts file. This command will be called after SSH has read the known hosts files and allows you to add additional entries on the fly, based on the information of the current connection attempt.
So, you could put something like this in your SSH configuration file:
Host 10.0.0.*
KnownHostsCommand /usr/bin/env printf "%H ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILUT1234567Xu2vvCE1likgUSOXLzEV123456783asaA"
[I am using the /usr/bin/env
trick here because SSH requires the path to the KnownHostsCommand
to be absolute and the path for printf
is not standardized. You can use the absolute path to printf
on your system instead if you want to.]
So, what this means is: if the host you are trying to connect to matches the pattern 10.0.0.*
, then add the result of calling the following command to the list of host keys. The command, in turn, uses the token %H
(meaning "the host name we are trying to look up") and the string from your question to construct a valid known hosts key line for whatever IP address you are currently trying to connect to.
No need to litter your known hosts file with 254 identical entries.