如何通过python Paramiko与ppk公钥进行ssh连接

时间:2011-12-05 08:51:52

标签: python ssh putty paramiko public-key

我正在使用Paramiko通过ssh连接到服务器。

基本身份验证效果很好,但我无法理解如何连接公钥。

当我用putty连接时,服务器告诉我:

Using username "root".
Authenticating with public key "rsa-key@ddddd.com"
Passphrase for key "rsa-key@ddddd.com": [i've inserted the passphrase here]
Last login: Mon Dec  5 09:25:18 2011 from ...

我用这个ppk文件连接到它:

PuTTY-User-Key-File-2: ssh-rsa
Encryption: aes256-cbc
Comment: rsa-key@dddd.com
Public-Lines: 4
[4 lines key]
Private-Lines: 8
[8 lines key]
Private-MAC: [hash]

使用基本身份验证我得到的错误(来自日志)是:

DEB [20111205-09:48:44.328] thr=1   paramiko.transport: userauth is OK
DEB [20111205-09:48:44.927] thr=1   paramiko.transport: Authentication type (password) not permitted.
DEB [20111205-09:48:44.927] thr=1   paramiko.transport: Allowed methods: ['publickey', 'gssapi-with-mic']

我试图包含该ppk文件并设置为auth_public_key,但是没有用。

你能帮助我吗?

4 个答案:

答案 0 :(得分:61)

好的@Adam和@Kimvais是对的,paramiko无法解析.ppk文件。

所以要走的路(感谢@JimB)是将.ppk文件转换为openssh私钥格式;这可以使用Puttygen所述的here来实现。

然后与它建立联系非常简单:

import paramiko
ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('<hostname>', username='<username>', password='<password>', key_filename='<path/to/openssh-private-key-file>')

stdin, stdout, stderr = ssh.exec_command('ls')
print stdout.readlines()
ssh.close()

答案 1 :(得分:12)

对我来说,我这样做:

import paramiko
hostname = 'my hostname or IP' 
myuser   = 'the user to ssh connect'
mySSHK   = '/path/to/sshkey.pub'
sshcon   = paramiko.SSHClient()  # will create the object
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error
sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed

对我很有用

答案 2 :(得分:5)

在Puttygen中创建Paramiko支持的有效DSA格式私钥。

点击转化,然后点击导出OpenSSH密钥

enter image description here

答案 3 :(得分:1)

@VonC's answer to a duplicate question

如果如前所述,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()