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

问题描述 投票:52回答:4

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

基本身份验证效果很好,但我不明白如何使用公钥进行连接。

当我连接腻子时,服务器告诉我这一点:

Using username "root".
Authenticating with public key "[email protected]"
Passphrase for key "[email protected]": [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: [email protected]
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,但是没有用。

你能帮我吗?

python ssh putty paramiko public-key
4个回答
69
投票

[确定@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()

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

为我工作很好]


5
投票

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


0
投票
import paramiko
from . import forms
def ToolsDisplay(request):

     if request.method=="POST": 
         form=forms.Tools(request.POST)
         if form.is_valid():
             cmd=form.cleaned_data['Choose_tool']
             print(cmd)
             user_name="root"  
             ip="10.80.xx.xx" 
             mySSHK = '/wfs/user/.ssh/authorized_keys'
             ssh_client=paramiko.SSHClient()
             ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
             ssh_client.connect(hostname=ip,username=user_name,key_filename=mySSHK)

             stdin,stdout,stderr=ssh_client.exec_command(cmd)
             stdout=stdout.readlines()

     else:
         form=forms.Tools()
         stdout=""
     my_dict={'stdout':stdout,'form':form}
     return render(request,'newpers/tools.html',context=my_dict)
© www.soinside.com 2019 - 2024. All rights reserved.