0

我正在尝试使用云功能将文件从 SFTP 服务器上传到 GCS 存储桶。但是这段代码不起作用。我能够sftp。但是当我尝试在GCS存储桶中上传文件时,它不起作用,要求是使用Python的云功能。

任何帮助将不胜感激。这是我正在尝试的示例代码。这段代码除了sftp.get("test_report.csv", bucket_destination). 请帮忙。

destination_bucket ="gs://test-bucket/reports"
with pysftp.Connection(host, username, password=sftp_password) as sftp:
    print ("Connection successfully established ... ")

    # Switch to a remote directory
    sftp.cwd('/test/outgoing/')
   
    bucket_destination = "destination_bucket"

    sftp.cwd('/test/outgoing/')
    if sftp.exists("test_report.csv"):
        sftp.get("test_report.csv", bucket_destination)
    else:
        print("doesnt exist")
4

2 回答 2

0

pysftp 不能直接与 GCP 一起工作。

Imo,无论如何,您实际上无法将文件直接从 SFTP 上传到 GCP,至少不能从另一台机器上运行的代码上传。但是您可以使用pysftpConnection.open(或者更好地使用ParamikoSFTPClient.open)和 GCS API来传输文件而不将其存储在中间机器上Blob.upload_from_file。这就是许多人所说的“直接”

client = storage.Client(credentials=credentials, project='myproject')
bucket = client.get_bucket('mybucket')
blob = bucket.blob('test_report.csv')

with sftp.open('test_report.csv', bufsize=32768) as f:
    blob.upload_from_file(f)

有关 GCP 代码的其余部分,请参阅如何在 Python 3 上将文件上传到 Google Cloud Storage?

有关目的bufsize,请参阅读取使用 Python Paramiko SFTPClient.open 方法打开的文件很慢


考虑不使用 pysftp,它是死项目。直接使用 Paramiko(代码基本相同)。参见pysftp vs. Paramiko

于 2022-01-30T05:49:50.277 回答
0

我根据您的回复得到了解决方案谢谢这里是代码

               bucket = client.get_bucket(destination_bucket)
              `blob = bucket.blob(destination_folder +filename)

                with sftp.open(sftp_filename, bufsize=32768) as f:
                    blob.upload_from_file(f)
于 2022-02-04T00:47:06.933 回答