Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PYSFTP - pass private-key as string/text instead of passing file path

I would like to pass my actual private-key value as argument instead of providing the file path.

I have used below code as of now:

import pysftp
import os

cnopts = pysftp.CnOpts()
if str(host_keys).lower() =='none':
    cnopts.hostkeys = None
else:
    cnopts.hostkeys.load(hostkeys)
filename = os.path.basename(localpath)
print(filename)
remotepath = os.path.join(remotefolder, filename)
print(remotepath)
with pysftp.Connection(host=hostname, port=int(port), username=username, password=password, cnopts=cnopts,private_key=private_key_filepath) as sftp:
    sftp.put(localpath, remotepath=remotepath)

Please suggest some way to pass it as text.

Example:

private_key='abcdmyprivatekeytext'

In actual scenario I will be placing my private-key text in secure vault.

like image 850
pooja shettigar Avatar asked Oct 16 '22 02:10

pooja shettigar


1 Answers

The pysftp can accept RSAKey in the private_key argument of Connection constructor:

# Set your private key as a string
PRIVATE_KEY = """-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----
"""

# Use 'io.StringIO' to read your string as a file-like object.
privkey = io.StringIO(PRIVATE_KEY)

# Use paramiko to create your RSAKey
ki = paramiko.RSAKey.from_private_key(privkey)

# Connect using your key with pysftp
conn = pysftp.Connection(host=HOST, username=USER, private_key=ki)

(originally posted by @Hana, but the answer is deleted now)

This use of private_key argument is not backed by documentation as of pysftp 0.2.9, but it works. Other key types (DSSKey, ECDSAKey, Ed25519Key) are not accepted.


If you need to use other keys types, use Paramiko directly:
SSH/SCP through Paramiko with key in string

The pysftp is just an abandoned wrapper around Paramiko.
Prefer using Paramiko directly: pysftp vs. Paramiko

like image 118
Martin Prikryl Avatar answered Oct 18 '22 23:10

Martin Prikryl