Paramiko: Add host_key to known_hosts permanently

If you want to add one specific key in runtime (without any file):

from paramiko import RSAKey
from paramiko.py3compat import decodebytes

client = SSHClient()

# known host key
know_host_key = "<KEY>"
keyObj = RSAKey(data=decodebytes(know_host_key.encode()))

# add to host keys
client.get_host_keys().add(hostname=HOST, keytype="ssh-rsa", key=keyObj)

# login to ssh hostname
client.connect(hostname=HOST, port=PORT, username=USER)...

source: https://github.com/paramiko/paramiko/blob/2.6.0/tests/test_hostkeys.py#L75-L84


From the package documentation, compare

client.load_system_host_keys(filename=None)

Load host keys from a system (read-only) file.  Host keys read with
this method will not be saved back by `save_host_keys`.

with

client.load_host_keys(filename)

Load host keys from a local host-key file.  Host keys read with this
method will be checked after keys loaded via `load_system_host_keys`,
but will be saved back by `save_host_keys` (so they can be modified).
The missing host key policy `.AutoAddPolicy` adds keys to this set and
saves them, when connecting to a previously-unknown server.

So to make Paramiko store any new host keys, you need to use load_host_keys, not load_system_host_keys. E.g.

client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))

But it's generally a good idea to avoid using AutoAddPolicy, since it makes you open to man-in-the-middle attacks. What I ended up doing was to generate a local known_hosts in the same folder as the script:

ssh -o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=./known_hosts user@host

and then load this file instead:

client.load_host_keys(os.path.join(os.path.dirname(__file__), 'known_hosts'))

This way I can distribute the known_hosts together with my script and run it on different machines without touching the actual known_hosts on those machines.