Jun 082019
 

Quite a while ago, I “borrowed” some inscrutable zsh magic to automatically add the contents of ~/.ssh/known_hosts to a known_hostsi variable and used that variable to perform host name completion for certain commands. Once ssh started hashing the known_hosts file, this broke and I was busy at the time and stopped using it.

Ages later, I’ve fixed it and enhanced it a bit (and arguably made it a bit simpler). Not only does it pick up host names from the known_hosts file but also adds a list from lxc-ls and adds a few static host names (with one exception, not shown). This is done by adding the following to .zshrc :-

knownhosts=( $(sudo -b lxc-ls) )
#       Pick up a list of hosts from lxc-ls
knownhosts+="localhost"
#       Add static hostnames
for x in $(grep -v "|" ~/.ssh/known_hosts | awk '{print $1}' | awk -F, '{printf "%s ", $1}')
do
  knownhosts+=$x
done
#       Pull a list of hosts out of ~/.ssh/known_hosts excluding the Hashed hosts.
zstyle ':completion:*:(ssh|scp|sftp|ping|nmap):*' hosts $knownhosts
#       Commands to use a list of known hosts with

That probably is not the most efficient code, but does have the advantage that it is relatively easy to follow.

One addition is to add the option HashKnownHosts no to ~/.ssh/config.

There is of course a risk associated with disabling the hashing of host names within the known_hosts file. If your host becomes compromised, malicious code can use that file to obtain a list of hosts with which there is a trust relationship making it easier for an attacker to pivot through your network.