35

If a host's operating system has been re-installed and had its public key regenerated sshing to it will of course fail because the new key doesn't match the old one.

Is there an easier way to tell ssh that you know that the host's key has changed and that you want it to be updated. I think it feels a bit error-prone to use a text editor or something like sed to remove the offending line.

55

Use ssh-keygen -R hostname to remove the hostname from your known_hosts file. The next time you connect, the new host key will be added to your known_hosts file.

9
TARGET_HOST=[hostname or IP]

# Remove the old key(s) from known_hosts
ssh-keygen -R $TARGET_HOST

# Add the new key(s) to known_hosts (and also hash the hostname/address)
ssh-keyscan -H $TARGET_HOST >> ~/.ssh/known_hosts

The next time you connect, you'll connect without being asked Are you sure you want to continue connecting (yes/no)? since the keys will already be in the known_hosts file.

  • 1
    see also the StrictHostKeyChecking in ~/.ssh/config – Jeff Schaller Apr 12 '16 at 18:17
  • 1
    I'd use a different variable name.... HOST is in some shells giving your your own hostname, so I'd prefer not to alter it (I know one can just then exit, or do this from a subshell, but still, why not thehost instead? or something. a ALLCAPS variable could collide with a reserved internal name. smallcase names should not.) – Olivier Dulac Nov 28 '17 at 12:33
  • These keys in known_hosts are prefixed by some stuff which begins with |1|. That stuff isn't appended to the file via this method, or am I wrong? what's the difference then, because what ssh-keyscan returns does not begin with |1| – Daniel F Sep 8 '18 at 21:49
  • 1
    (@DanielF+) if you use hashed format and accepted the key(s) in ssh there are separate entries for the host name and its address(es), so you should ssh-keygen -R each of them to avoid conflict – dave_thompson_085 Sep 9 '18 at 5:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.