Search code examples
pythoncronparamikoopenssh

paramiko only as cron job not valid RSA private key


Paramiko script is running great from interactive terminal using id_rsa. When run as a cron job suddenly it finds the id_rsa to be invalid. Test 777 permissions have been set on all related files to no avail. Logs show that the job is being run as the proper user.

paramiko.ssh_exception.SSHException: not a valid RSA private key file

So, it seems this if statement at end of block is being fulfilled only as cron job: `

  def _read_private_key(self, tag, f, password=None):
            lines = f.readlines()
            start = 0
            beginning_of_key = "-----BEGIN " + tag + " PRIVATE KEY-----"
            while start < len(lines) and lines[start].strip()
                                                 != beginning_of_key:
            start += 1
        if start >= len(lines):
            raise SSHException("not a valid " + tag + " private key file")
` 

Any insights appreciated.

EDIT: My code to load key try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy) client.connect(hostname = '<target>', key_filename = '/home/user/.ssh/id_rsa',username='root')


Solution

  • I faced the 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 and then give that path to "key_filename"

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

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