此代码可以帮助我建立一个shh连接。我知道set_missing_host_key_policy
在known_hosts
找不到密钥时会有帮助。但它的行为与实际的ssh
不同,因为在我第一次运行此代码之后,我认为host_key
会被添加到known_hosts
并且我不需要函数set_missing_host_key_policy()
了。但是,我错了(paramiko.ssh_exception.SSHException)
。如何使用host_key
将known_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))
答案 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)
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()