Paramiko: Creating a PKey from a public key string

2019-07-03 14:58发布

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.

2条回答
Deceive 欺骗
2楼-- · 2019-07-03 15:31

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(..., ...)
查看更多
Evening l夕情丶
3楼-- · 2019-07-03 15:34

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.

查看更多
登录 后发表回答