【问题标题】:how to use a paramiko.PKey() in the .connect() method?如何在 .connect() 方法中使用 paramiko.PKey()?
【发布时间】:2014-12-09 19:44:44
【问题描述】:

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

即使密钥看起来正确,以下代码也会在 .connect() 上引发 paramiko.ssh_exception.AuthenticationException: Authentication failed.

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

我尝试在key 中添加\\n\n,没有任何更改(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.

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

【问题讨论】:

    标签: python ssh paramiko


    【解决方案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 现在可以根据问题中的代码传递给参数

    【讨论】:

      猜你喜欢
      • 2016-02-28
      • 2016-01-02
      • 2020-06-15
      • 1970-01-01
      • 2021-05-02
      • 2018-09-09
      • 1970-01-01
      • 2017-10-11
      • 2014-06-08
      相关资源
      最近更新 更多