Search code examples
pythonsshparamikossh-keys

Paramiko: Creating a PKey from a public key string


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.


Solution

  • 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(..., ...)