Paramiko:将 host_key 永久添加到 known_hosts [英] Paramiko: Add host_key to known_hosts permanently
问题描述
此代码帮助我建立 ssh 连接.我知道 set_missing_host_key_policy
在 known_hosts
中找不到密钥时会有所帮助.但它的行为不像实际的 ssh
,因为在我第一次运行此代码后,我认为 host_key
将被添加到 known_hosts
并且我不再需要 set_missing_host_key_policy()
函数.但是,我错了(paramiko.ssh_exception.SSHException)
.如何使用 paramiko
将 host_key
永久添加到 known_hosts
?(因为后端代码的某个部分是用'C'编写的,它需要在known_hosts
中找到host_key
)
This code helps me make an ssh 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))
推荐答案
从包文档中,比较
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`.
与
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.
所以要让Paramiko 存储任何新的主机密钥,您需要使用load_host_keys
,而不是load_system_host_keys
.例如
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'))
但是避免使用AutoAddPolicy
通常是个好主意,因为它会让您容易受到中间人攻击.我最终做的是在与脚本相同的文件夹中生成一个本地 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
然后加载这个文件:
client.load_host_keys(os.path.join(os.path.dirname(__file__), 'known_hosts'))
通过这种方式,我可以将 known_hosts
与我的脚本一起分发,并在不同的机器上运行它,而无需触及这些机器上的实际 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.
这篇关于Paramiko:将 host_key 永久添加到 known_hosts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!