Paramiko: "not a valid RSA private key file"

I am trying connect to server using following spinet

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ip = ['x.x.x.x']
key_file = "/Users/user/.ssh/id_rsa"

key = paramiko.RSAKey.from_private_key_file(key_file)
ssh.load_system_host_keys()
ssh.connect(ips, port=22, username='XYZ', pkey=key, timeout=11)

But I am getting an error:

not a valid RSA private key file


Solution 1:

I faced a similar situation and ssh-keygen comes to my help. You should make a copy of id_rsa and convert it to RSA type with ssh-keygen.

To Convert "BEGIN OPENSSH PRIVATE KEY" to "BEGIN RSA PRIVATE KEY"

ssh-keygen -p -m PEM -f ~/.ssh/id_rsa

Solution 2:

Recent versions of OpenSSH (7.8 and newer) generate keys in new OpenSSH format by default, which starts with:

-----BEGIN OPENSSH PRIVATE KEY-----

That format is fully supported by the Paramiko since version 2.7.1 (2019-12-09) only.


If you are stuck with an older version of Paramiko, you can use ssh-keygen to convert the key to the classic OpenSSH format:

ssh-keygen -p -f file -m pem -P passphrase -N passphrase

(if the key is not encrypted with a passphrase, use "" instead of passphrase)

For Windows users: Note that ssh-keygen.exe is now built-in in Windows 10. And can be downloaded from Microsoft Win32-OpenSSH project for older versions of Windows.


On Windows, you can also use PuTTYgen (from PuTTY package):

  • Start PuTTYgen
  • Load the key
  • Go to Conversions > Export OpenSSH key.
    For RSA keys, it will use the classic format.

If you are creating a new key with ssh-keygen, just add -m PEM to generate the new key in the classic format:

ssh-keygen -m PEM

Note that you can get the error, also when you are trying to use a completely different key format, like ssh.com or PuTTY .ppk. Then you will have to convert the key in any case.

  • For ssh.com format, see Paramiko: "not a valid DSA private key file".
  • For PuTTY .ppk format, use PuTTYgen as shown above.