Paramiko:永久地将host_key添加到known_hosts

时间:2016-09-16 03:10:22

标签: python ssh paramiko

此代码可以帮助我建立一个shh连接。我知道set_missing_host_key_policyknown_hosts找不到密钥时会有帮助。但它的行为与实际的ssh不同,因为在我第一次运行此代码之后,我认为host_key会被添加到known_hosts并且我不需要函数set_missing_host_key_policy()了。但是,我错了(paramiko.ssh_exception.SSHException)。如何使用host_keyknown_hosts永久添加到paramiko? (由于后端代码的某些部分是用' C'并且需要在host_key中找到known_hosts

还是我误解了什么?我需要一些指导......

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))

3 个答案:

答案 0 :(得分:12)

从包文档中,比较

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。 E.g。

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

避免使用AutoAddPolicy通常是一个好主意,因为它会让你对中间人攻击开放。我最终做的是在与脚本相同的文件夹中生成本地known_hosts

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。

答案 1 :(得分:1)

如果要在运行时添加一个特定的密钥(不包含任何文件):

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

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

答案 2 :(得分:0)

##使用paramiko远程添加用户ssh
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()