Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically updating known_hosts file when host key changes using Paramiko

Currently I am using Paramiko (in Python) to execute remote command on a node. At times, remote nodes change theirs public key, and consequently Paramiko fails as fingerprints do not match. Is there a way to update the keys in known_hosts file when they change? If this is not possible is there any other way to ignore the warning thrown?

Currently I have a hacky solution where known_hosts file is deleted before making the call which is not good.

like image 375
pkumarn Avatar asked Nov 22 '17 15:11

pkumarn


People also ask

What key is stored in known_hosts?

The known_hosts File is a client file containing all remotely connected known hosts, and the ssh client uses this file. This file authenticates for the client to the server they are connecting to. The known_hosts file contains the host public key for all known hosts.

What is host key Paramiko?

HostKeys (filename=None) Representation of an OpenSSH-style “known hosts” file. Host keys can be read from one or more files, and then individual hosts can be looked up to verify server keys during SSH negotiation. A HostKeys object can be treated like a dict; any dict lookup is equivalent to calling lookup .

What is the purpose of the known_hosts file?

Definition(s): A file associated with a specific account that contains one or more host keys. Each host key is associated with an SSH server address (IP or hostname) so that the server can be authenticated when a connection is initiated.


1 Answers

BadHostKeyException is thrown when a host key changes, as that is a sign of the connecting being hijacked (aka Man-in-the-middle attack).

You should never blindly ignore the exception. Unless maybe, if you connect to a server located in the same private network as your client.

In your specific case, a better strategy is to preserve host keys during server reinstall.


Anyway, if you really do not care about security, and are willing to blindly accept any host key:

  • do not call SSHClient.load_host_keys, so that you start with a blank list of known host keys;

  • and use AutoAddPolicy, to automatically accept host keys of new hosts (all hosts are new due to the previous point):

    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
like image 76
Martin Prikryl Avatar answered Sep 23 '22 13:09

Martin Prikryl