71

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.

1

2 Answers 2

97

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

31
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.

7
  • 1
    see also the StrictHostKeyChecking in ~/.ssh/config
    – Jeff Schaller
    Apr 12, 2016 at 18:17
  • 3
    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.) Nov 28, 2017 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, 2018 at 21:49
  • 2
    (@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 Sep 9, 2018 at 5:47
  • 1
    Worth noting that the question being asked specifically states "when you know that a host's key has changed."
    – Earl Ruby
    Nov 30, 2022 at 1:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .