6

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.

4

3 回答 3

6

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(..., ...)
于 2014-06-15T21:34:53.987 回答
1

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.

于 2013-03-30T20:32:56.577 回答
0

To add onto the solution provided for the Transport Client. Here is my solution for adding a string public key to the SSH Client:

my_pub_key = "xx.xx.xx.xx ecdsa-sha2-nistp256 mlzdHAyNT....."
my_host = my_pub_key.split(' ')[0]
password = 'myFavortitePassword'
username = 'myUsername'

ssh_client=paramiko.SSHClient()

host_key_policy = paramiko.MissingHostKeyPolicy()
host_key_policy.missing_host_key(ssh_client, my_host, my_pub_key)

ssh_client.connect(hostname= my_host
                            ,username=username
                            ,password=password
                            ,port=22
                            ,look_for_keys=False)
于 2020-06-02T05:37:54.970 回答