Paramiko: Add host_key to known_hosts permanently

隐身守侯 提交于 2019-12-09 09:20:38

问题


This code helps me make an shh connection. I know that set_missing_host_key_policy helps when the key is not found in the known_hosts. But it is not behaving like the actual ssh, because after the first time I run this code, I assumed that that the host_key would be added to known_hosts and that I need not have the function set_missing_host_key_policy() anymore. But, I was wrong (paramiko.ssh_exception.SSHException). How can I permanently add the host_key to known_hosts using paramiko? (As a certain part of the backend code is written in 'C' and it needs the host_key to be found in known_hosts)

Or am I misunderstanding something? I would need some guidance on this...

import paramiko

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=str(host),username =str(user),password=str(pswd))

回答1:


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.




回答2:


##add user remotely ssh using paramiko
import paramiko
import os

ssh= paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.10.49', port=22,username='root', password='abc@123')
def addnewuser():

    uname=input("Type your new Create userName")
    upass=input("Enter Password")



    os.system("useradd -m -p "+upass+" "+uname)

addnewuser()


来源:https://stackoverflow.com/questions/39523216/paramiko-add-host-key-to-known-hosts-permanently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!