使用PGP使用Python对存储在SFTP服务器上的文件进行解密

2024-06-11 02:48:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我在该服务器上使用*.PGP文件设置了一个SFTP。我用来从python连接到SFTP的包是Paramiko,如下所示

import paramiko

transport = paramiko.Transport(json_data["host"], 22)
transport.connect(username=json_data["username"], password=json_data["password"])
sftp = paramiko.SFTPClient.from_transport(transport)

另外,我使用pgpy对消息进行解密。基本上,密钥来自google云存储桶,将其加载到密钥链并解密文件

我已经为一个本地文件设置了解密,但似乎不知道如何在服务器上解密消息

我无法使用get函数,因为我将在Google云函数上运行此代码,因此无法访问本地目录

是否有任何方法可以将文件加载到Python中,解密文件,然后将其加载到Pandas中。结束文件是一个.CSV文件

用于解密本地文件的实际代码

import pgpy
key = pgpy.PGPKey().from_file("path/to/file/keyfile.asc")

with key[0].unlock("password") as ukey:
    message = pgpy.PGPMessage().from_file("path/to/file/file.pgp")
    f = ukey.decrypt(message).message
    print(f)

这将在本地解密消息


Tags: 文件fromimport服务器json消息paramikomessage
2条回答

您应该能够download the file from SFTP server to memory(例如,to BytesIO对象)。然后使用^{}

类似这样(未经测试):

with io.BytesIO() as fl:
    sftp.getfo(file_name, fl)
    fl.seek(0)
    bytes = fl.read()
    message = pgpy.PGPMessage().from_blob(bytes)

过了一段时间我就知道怎么做了, 准备来自SFTP的传入数据

x = sftp.open("File.csv.pgp", 'rb').read()
    toread = io.BytesIO()
    toread.write(x)
    toread.seek(0)

然后导入来自Google云存储的密钥mine并打开密钥

with gcsfs.GCSFileSystem(project="proj").open('path/to/*.asc','rb') as token:
   creds = pgpy.PGPKey().from_blob(token.read())#load key
   with creds[0].unlock("pass") as ukey:
       message = pgpy.PGPMessage().from_blob(toread.read())#load file body
       decryptedmessage = ukey.decrypt(message).message#decryt file body
       decryptedmessagestr = decryptedmessage.decode()#decode bytes
       DMIo = io.StringIO(decryptedmessagestr)#convert decoded bytes to string
       dataframe = pd.read_csv(DMIo) #insert into pandas

相关问题 更多 >