Search code examples
python-2.7paramikostringio

How to provide private key as string to paramiko for an ssh connection?


I am trying to use ssh to connect to server using Python paramiko package.

When I tried to ssh into server using "pem" key then it worked but when I tried it by taking private key content in a string it shows an error.

With the following code:

    import paramiko
    import StringIO
    content="-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQE ----whatever content"
    private_key = StringIO.StringIO(content)
    k = paramiko.RSAKey.from_private_key(private_key)
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    host="XX.XX.XX.XXX"
    c.connect( hostname = host,username="ec2-user", pkey = k )
    print "Connected to " + host`

I get the following output:

Traceback (most recent call last):
  File "one.py", line 6, in <module>
    k = paramiko.RSAKey.from_private_key(private_key)
  File "/home/ec2-user/abc/local/lib/python2.7/site-packages/paramiko/pkey.py", line 217, in from_private_key
    key = cls(file_obj=file_obj, password=password)
  File "/home/ec2-user/abc/local/lib/python2.7/site-packages/paramiko/rsakey.py", line 42, in __init__
    self._from_private_key(file_obj, password)
  File "/home/ec2-user/abc/local/lib/python2.7/site-packages/paramiko/rsakey.py", line 167, in _from_private_key
    data = self._read_private_key('RSA', file_obj, password)
  File "/home/ec2-user/abc/local/lib/python2.7/site-packages/paramiko/pkey.py", line 277, in _read_private_key
    raise SSHException('not a valid ' + tag + ' private key file')
paramiko.ssh_exception.SSHException: not a valid RSA private key file

Can anyone suggest what could be the problem?


Solution

  • Private key file is a multiline file.

    So when using it as a string, preserve the content structure as it is to keep it valid.

    content = """-----BEGIN RSA PRIVATE KEY-----
                  MIIEpgSIJOBAAKCAQEAqwH5fWIbtFRankLqvtnQ6OKwmIa49i
                  ..........................................
                  -----END RSA PRIVATE KEY-----"""
    
    private_key = StringIO.StringIO(content)
    k = paramiko.RSAKey.from_private_key(private_key)