【问题标题】:Use PGP to decrypt a file stored on SFTP server with Python使用 PGP 使用 Python 解密存储在 SFTP 服务器上的文件
【发布时间】:2020-07-14 15:42:05
【问题描述】:

我有一个在该服务器上使用 *.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 来解密消息。基本上,密钥来自谷歌云存储桶并将其加载到钥匙串中并解密文件

我已经为本地文件设置了解密,但似乎无法弄清楚如何解密服务器上的消息。

我无法使用 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)

这将在本地解密消息。

【问题讨论】:

    标签: python sftp paramiko pgp


    【解决方案1】:

    您应该能够download the file from SFTP server to memory(例如BytesIO 对象)。然后使用PGPMessage().from_blob

    类似这样的东西(未经测试):

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

    【讨论】:

      【解决方案2】:

      一段时间后我想出了如何做到这一点, 准备来自 SFTP 的传入数据

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

      然后导入来自谷歌云存储的密钥并打开密钥

      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
      

      【讨论】:

      • sftp.getfo(file_name, toread) 应该更有效——无论是在时间还是内存消耗方面。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多