2

I have an SSH key stored in a variable as I'm using a cloud function and don't have access to a filesystem. For example:

with SSHTunnelForwarder(
   ssh_address_or_host='my-host', 
   ssh_username='my-user',
   ssh_pkey='/home/david/.ssh/id_rsa' # this
) as tunnel:

Instead of passing the path to the ssh_pkey file, how can I hardcode that as a string? Yes, I will move it to an environmental variable or something else, but for testing, is there a way to pass it a string?

David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

1

As @TimRoberts commented, the ssh_pkey accepts paramiko.pkey.PKey instance, not only a path to a key file.

For an example how to construct PKey from a string, see:
SSH/SCP through Paramiko with key in string

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
1

This is how I solved it for GCP Cloud Functions. First I used Python to print out a base64 encoded key of my key file 'temp_key.pem'. The reason I did this was because copying and pasting the key didn't work in the GCP environment variables even though it did locally:

import base64
with open('temp_key.pem', 'rb') as f:
    blob = base64.b64encode(f.read())

print(blob)
for_google_cloud_function = blob.decode('utf-8')
print(for_google_cloud_function)

The output of this I used an my environment variable SSH_KEY_BLOB. In my GCP Cloud Function I then added this (I've missed out the line getting it from the GCP environment variables):

# decode key back into a useable form from base64
SSH_KEY_BLOB_DECODED = base64.b64decode(SSH_KEY_BLOB)
SSH_KEY = SSH_KEY_BLOB_DECODED.decode('utf-8')

# pass key to parmiko to get your pkey
pkey = paramiko.RSAKey.from_private_key(io.StringIO(SSH_KEY))

# setup your SSHTunnel like normal
server = SSHTunnelForwarder(
    remote_server_ip,
    ssh_username=SSH_USERNAME,
    ssh_pkey=pkey,
    remote_bind_address=('127.0.0.1', 27017)
)

That way the key is not hard coded and the function is self sufficient from the file. They may be better ways but this worked for me.

Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50