title: How to Securely Add a List of Hosts to known_hosts File
body: <p>I have a file that contains ~1000 hosts, one host per line. For each host, I want to check if an entry for the host already exists in the <code>known_hosts</code> file. If one does not, I want to add the host to the <code>known_hosts</code> file. Otherwise, I want to update the existing entry. I would like to use the <code>-H</code> option to hash all entries in <code>known_hosts</code>. I have already run the command <code>ssh-keygen -H ~/.ssh/known_hosts</code> to hash the existing entries.</p>
  
  <p>Here is a simple loop that I put together:</p>
  
  <pre><code>while read LINE; do
      # Remove entry if it exists
      ssh-keygen -R $LINE
      # Append new hashed key to file
      ssh-keyscan -H $LINE &gt;&gt; ~/.ssh/known_hosts
  done &lt; $HOST_FILE
  </code></pre>
  
  <p>Is this method secure? If not, what is the recommended way of doing this? The reason I am doing this is to disable typing "yes" 1000 times to allow every new host to be added to <code>known_hosts</code> for scripting purposes.</p>