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

时间:2014-12-09 10:28:43

标签: python ssh paramiko

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

以下代码在paramiko.ssh_exception.AuthenticationException: Authentication failed.上引发.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

我在\\n中尝试\n以及key,没有任何更改(paramiko.PKey()都接受)。

上面的代码也将密钥转储到文件以测试命令行ssh连接,该连接成功:

host1$ chmod 600 key.priv
host1$ ssh root@10.0.0.1 -i key.priv
root@host2 #

是否有特定格式的密钥要传递给paramiko.PKey()?其docs声称

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

在我的情况下没有发生(因此我假设密钥的格式是可接受的编辑:我用随机字符串检查并且仍然接受“密钥”,所以没有检查是取决于密钥的正确性)

1 个答案:

答案 0 :(得分:1)

我使用another answer的帮助找到了解决方案:

# 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)

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