Python 如何在.connect()方法中使用paramiko.PKey()?

Python 如何在.connect()方法中使用paramiko.PKey()?,python,ssh,paramiko,Python,Ssh,Paramiko,我想使用传递给paramiko的.connect()方法的OpenSSH密钥连接到ssh服务器 以下代码引发paramiko.ssh\u exception.AuthenticationException:身份验证失败。在.connect()上,即使密钥看起来正确: import paramiko # the key below is shortened for readability, it is made of blocks ending with \\n - in other words

我想使用传递给paramiko的
.connect()
方法的OpenSSH密钥连接到ssh服务器

以下代码引发
paramiko.ssh\u exception.AuthenticationException:身份验证失败。
.connect()
上,即使密钥看起来正确:

import paramiko
# the key below is shortened for readability, it is made of blocks ending with \\n - in other words
# the return-carriage in the original file was replaced with \\n
key = "-----BEGIN RSA PRIVATE KEY-----\\nMIIEpQIBA(...)b+iro=\\n-----END RSA PRIVATE KEY-----\\n"

# this is to dump the key for checking a command-line connection with that key
with open("key.priv", "w") as f:
    f.write(key.replace('\\n', '\n'))

key = paramiko.PKey(data=key)
params = {
            'hostname': '10.0.0.1',
            'port': 22,
            'username': 'root',
            'look_for_keys': False,
            'timeout': 5,
            'pkey' : key
}  
ssh = paramiko.SSHClient()  # Initiate SSH client
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # allow to add unknown ssh key
res = ssh.connect(**params)
运行代码:

Traceback (most recent call last):
  File "C:/Users/aa/testsshkey.py", line 19, in <module>
    res = ssh.connect(**params)
  File "C:\Python27\lib\site-packages\paramiko\client.py", line 307, in connect
    look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
  File "C:\Python27\lib\site-packages\paramiko\client.py", line 519, in _auth
    raise saved_exception
paramiko.ssh_exception.AuthenticationException: Authentication failed.

Process finished with exit code 1
传递给
paramiko.PKey()
的密钥是否有特定格式?它声称

Raises SSHException: 
if a key cannot be created from the data or msg given, or no key was passed in.

这在我的情况下不会发生(因此我假设密钥的格式是可接受的编辑:我使用随机字符串进行了检查,并且“密钥”仍然被接受,因此不会对密钥的正确性进行检查)

我使用以下帮助找到了解决方案:

现在可以根据问题中的代码传递给参数

Raises SSHException: 
if a key cannot be created from the data or msg given, or no key was passed in.
# note the single backslash in \n
key = "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEAwK(...)J90XccMb+iro=\n-----END RSA PRIVATE KEY-----\n"
keyfile = StringIO.StringIO(key)
key = paramiko.RSAKey.from_private_key(keyfile)