Paramiko PKey.from_private_key_file 给我“__init__() 得到了一个意外的关键字参数 'filename'”

Paramiko PKey.from_private_key_file gives me "__init__() got an unexpected keyword argument 'filename'"

我从 paramiko 那里得到了非常奇怪的行为:

bla=paramiko.pkey.PKey(msg=None,data=None).from_private_key_file()
TypeError                                 Traceback (most recent call last)
<ipython-input-32-13288f655ecf> in <module>
----> 1 paramiko.pkey.PKey(msg=None,data=None).from_private_key_file()

TypeError: from_private_key_file() missing 1 required positional argument: 'filename'

这里它告诉我我需要一个文件名,但是每当我尝试指定任何内容时:

bla=paramiko.pkey.PKey(msg=None,data=None).from_private_key_file('key')
                                 Traceback (most recent call last)
<ipython-input-33-5fa0cf9b6317> in <module>
----> 1 bla=paramiko.pkey.PKey(msg=None,data=None).from_private_key_file('key')

~/anaconda3/lib/python3.7/site-packages/paramiko/pkey.py in from_private_key_file(cls, filename, password)
    233         :raises: `.SSHException` -- if the key file is invalid
    234         """
--> 235         key = cls(filename=filename, password=password)
    236         return key
    237 

TypeError: __init__() got an unexpected keyword argument 'filename'

谁能给我解释一下这是怎么回事?我完全糊涂了。

  1. PKey.from_private_key_file 是一种 class 方法。
  2. 不使用PKey base class directly. You have to use the correct descendant class, like RSAKey, DSSKey

正如 documentation 所说:

Through the magic of Python, this factory method will exist in all subclasses of PKey (such as RSAKey or DSSKey), but is useless on the abstract PKey class.

正确的代码如下:

key = paramiko.RSAKey.from_private_key_file('key')

尽管如果您打算将密钥与 SSHClient, you can pass the filename directly to key_filename argument of SSHClient.connect 一起使用,并且您根本不必处理密钥加载。