无法使用Python通过SSH密钥登录

时间:2020-08-20 16:46:49

标签: python authentication ssh paramiko

我正在尝试使用python在服务器中通过ssh登录。我已经使用腻子生成了密钥。当我在腻子中使用此键时,它的工作正常。但是当我尝试从python连接时,它表示身份验证失败

import paramiko

router_ip = "157.230.16.214"
router_username = "root"

ssh = paramiko.SSHClient()

# Load SSH host keys.
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(router_ip, 
            username=router_username,
            look_for_keys="private.ppk" ) #This is private file and its have in same folder


ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("show ip route")

output = ssh_stdout.readlines()
ssh.close()

Server Error Message

1 个答案:

答案 0 :(得分:0)

如果如前所述,Paraminko不支持PPK密钥,则如此处所示,官方解决方案是使用Puttygen

但是您也可以使用Python library CkSshKey直接在程序中进行相同的转换。

请参阅“ Convert PuTTY Private Key (ppk) to OpenSSH (pem)

import sys
import chilkat

key = chilkat.CkSshKey()

#  Load an unencrypted or encrypted PuTTY private key.

#  If  your PuTTY private key is encrypted, set the Password
#  property before calling FromPuttyPrivateKey.
#  If your PuTTY private key is not encrypted, it makes no diffference
#  if Password is set or not set.
key.put_Password("secret")

#  First load the .ppk file into a string:

keyStr = key.loadText("putty_private_key.ppk")

#  Import into the SSH key object:
success = key.FromPuttyPrivateKey(keyStr)
if (success != True):
    print(key.lastErrorText())
    sys.exit()

#  Convert to an encrypted or unencrypted OpenSSH key.

#  First demonstrate converting to an unencrypted OpenSSH key

bEncrypt = False
unencryptedKeyStr = key.toOpenSshPrivateKey(bEncrypt)
success = key.SaveText(unencryptedKeyStr,"unencrypted_openssh.pem")
if (success != True):
    print(key.lastErrorText())
    sys.exit()