My following Python code
import paramiko client = paramiko.SSHClient() client.load_system_host_keys() client.connect(hostname=hostname, username=username)
Fails with this error message
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/paramiko/client.py", line 435, in connect
self._auth(
File "/usr/lib/python3/dist-packages/paramiko/client.py", line 764, in _auth
raise saved_exception
File "/usr/lib/python3/dist-packages/paramiko/client.py", line 734, in _auth
key = self._key_from_filepath(
File "/usr/lib/python3/dist-packages/paramiko/client.py", line 586, in _key_from_filepath
key = klass.from_private_key_file(key_path, password)
File "/usr/lib/python3/dist-packages/paramiko/pkey.py", line 206, in from_private_key_file
key = cls(filename=filename, password=password)
File "/usr/lib/python3/dist-packages/paramiko/rsakey.py", line 55, in __init__
self._from_private_key_file(filename, password)
File "/usr/lib/python3/dist-packages/paramiko/rsakey.py", line 175, in _from_private_key_file
data = self._read_private_key_file("RSA", filename, password)
File "/usr/lib/python3/dist-packages/paramiko/pkey.py", line 279, in _read_private_key_file
data = self._read_private_key(tag, f, password)
File "/usr/lib/python3/dist-packages/paramiko/pkey.py", line 289, in _read_private_key
raise SSHException("not a valid " + tag + " private key file")
paramiko.ssh_exception.SSHException: not a valid RSA private key file
This happens to a particular remote server. But, it does connect to my another server successfully without any issue.
I also do not want to change my public key. Otherwise, I will need to re-add it to all my remotes.
How to fix this problem?
If you look at the first line of your private key,
head -n 1 ~/.ssh/id_rsa
I suspect what you will see is this OpenSSH key header
-----BEGIN OPENSSH PRIVATE KEY-----
instead of standard RSA key header
-----BEGIN RSA PRIVATE KEY-----
To resolve this problem, you will need to convert your OpenSSH key to the standard RSA key. This will not regenerate your key and your public key will remain the same as before. Thus, you do not need to regenerate it.
This command will overwrite your current OpenSSH private key. Therefore, I recommend you taking a backup from it first before applying it:
ssh-keygen -p -N "" -m pem -f ~/.ssh/id_rsa