Paramiko: Creating a PKey from a public key string

≯℡__Kan透↙ 提交于 2019-12-13 14:01:07

问题


I'm trying to use the SSH protocol at a low level (i.e. I don't want to start a shell or anything, I just want to pass data). Thus, I am using Paramiko's Transport class directly.

I've got the server side done, but now I'm hitting a wall over something silly. For the client to connect to the server, the Transport's connect method takes as two PKey objects as argument: The private key of the client (pkey), and the public key of the server (hostkey).

The PKey class is described as "Base class for public keys". Yet the problem is that I can't figure out how to create such a PKey object out of just an ssh public key (i.e. a string ssh-whatever AAblablabla). It has methods for building such an object out of a private key, but obviously I don't want the client to know the server's private key.

I feel like I'm overlooking something simple, but I can't find info on doing that on the web; most tutorials out there use the higher-level SSHClient class which loads the system's known_hosts keys.


回答1:


Had to solve this problem again in another context that wasn't just for key comparison (it was for signature checking). Here's the proper way to do it. In retrospect it was pretty simple, but hardly documented at all.

# For a public key "ssh-rsa AAblablabla...":
key = paramiko.RSAKey(data=base64.b64decode('AAblablabla...'))
key.verify_ssh_sig(..., ...)



回答2:


Worked around it by calling the individual methods described in the connect method documentation:

clientPrivateKey = paramiko.RSAKey.from_private_key_file(...)
transport = paramiko.Transport(...)
knownServerKey = 'ssh-rsa AAblablabla'.split(' ', 3)
transport.start_client()
serverKey = transport.get_remote_server_key()
if serverKey.get_name() == knownServerKey[0] and serverKey.get_base64() == knownServerKey[1]:
    # Valid key
    transport.auth_publickey('username', clientPrivateKey)
    channel = transport.open_channel('...')
else:
    # Invalid key

This is more or less what the connect method does anyway.

I am still open to better/shorter suggestions though. As it stands, the hostkey parameter of the connect method seems unusable.



来源:https://stackoverflow.com/questions/15722704/paramiko-creating-a-pkey-from-a-public-key-string

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