如何通过Python Paramiko使用ppk公钥连接SSH

79 投票
4 回答
196737 浏览
提问于 2025-04-17 07:42

我正在使用 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 个回答

9

要在Puttygen中创建一个Paramiko支持的有效DSA格式私钥,首先你需要做以下步骤。

点击“转换”选项,然后选择“导出OpenSSH密钥”。

在这里输入图片描述

27

对我来说,我是这样做的:

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

这样对我来说效果还不错。

95

好的,@Adam 和 @Kimvais 说得对,Paramiko 不能解析 .ppk 文件。

所以解决办法是把 .ppk 文件转换成 OpenSSH 私钥格式;这个可以通过 PuTTYgen 来实现,具体步骤可以参考 这里

然后用这个连接就非常简单了:

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

撰写回答