gpt4 book ai didi

Python PYSFTP - 将私钥作为字符串/文本传递而不是传递文件路径

转载 作者:行者123 更新时间:2023-12-04 04:02:49 26 4
gpt4 key购买 nike

我想将我的实际私钥值作为参数传递,而不是提供文件路径。
到目前为止,我已经使用了以下代码:

def upload_file_to_remote(hostname, port, username, password, private_key_filepath, localpath, remotefolder, host_keys):
import pysftp
import os

if password=="None":
password=None

try:

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:
print sftp
sftp.put(localpath, remotepath=remotepath)
except IOError as e:
result="SFTP Failed "+str(e)
return result
except pysftp.exceptions.ConnectionException as e:
return "SFTP Failed "+str(e)
except pysftp.exceptions.CredentialException as e:
return "SFTP Failed "+str(e)
except pysftp.exceptions.HostKeysException as e:
return "SFTP Failed "+str(e)
except Exception as e:
return "SFTP Failed "+str(e)
return {'status':'pass','result' : remotepath}

#print(upload_file_to_remote(hostname, port, username, password, private_key_filepath, localpath, remotefolder,host_keys))


upload_file_to_remote(hostname, port, username, password, private_key_filepath, localpath, remotefolder, host_keys)
请建议某种方式将其作为文本传递。
例子:
private_key='abcdmyprivatekeytext'

upload_file_to_remote(hostname, port, username, password, private_key, localpath, remotefolder, host_keys)
在实际情况下,我会将我的私钥文本放在安全保险库中。

最佳答案

pysftp 可以接受 RSAKey private_key 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)
(最初由@Hana 发布,但现在已删除答案)
此使用 private_key自 pysftp 0.2.9 起,参数不受文档支持,但它有效。不接受其他 key 类型( DSSKeyECDSAKeyEd25519Key )。

如果需要使用其他键类型,直接使用Paramiko:
SSH/SCP through Paramiko with key in string
pysftp 只是 Paramiko 的包装器。
pysftp vs. Paramiko

关于Python PYSFTP - 将私钥作为字符串/文本传递而不是传递文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62831499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com