Search code examples
pythonsshsftpparamikoscp

Not a valid OPENSSH private key file - Paramiko


I'm trying to connect to a host using paramiko. I'm able to successfully connect to the host through winscp using the private key, but the script fails with below error

raise SSHException("not a valid {} private key file".format(tag)) paramiko.ssh_exception.SSHException: not a valid OPENSSH private key file

import paramiko
ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('hostname.com', username='user', key_filename='private.ppk')

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

Any suggestion would be appretiated,

Solution

  • Paramiko is in python and most likely wants a PEM file encoding for the key. Winscp and Putty use ppk which is typically used on Microsoft based SSH systems. Putty comes with a tool to covert the ppk to OpenSSH called PuttyGen.

    1. Open PuttyGen

    2. Select Load and pick your PPK file you wish to convert

    3. Menu Conversion > Export OpenSSH Key

    4. Answer Yes to "Do you want to save this key without a passphrase?" Doing this will store the key unencrypted so be very careful with it and don't copy it to insecure locations.

    5. enter your new filename and a suffix of .pem.

    You now have a PEM encoded key that will work with OpenSSH and paramiko.