我正在嘗試將檔案從 SFTP 服務器遞回移動到 S3,可能使用boto3. 我也想保留檔案夾/檔案結構。我想這樣做:
import pysftp
private_key = "/mnt/results/sftpkey"
srv = pysftp.Connection(host="server.com", username="user1", private_key=private_key)
srv.get_r("/mnt/folder", "./output_folder")
然后獲取這些檔案并使用boto3. 但是,服務器上的檔案夾和檔案很多,層次很深,而且體積也很大。所以我的機器最終耗盡了記憶體和磁盤空間。我正在考慮一個腳本,我可以在其中下載單個檔案并上傳單個檔案,然后洗掉并重復。
我知道這需要很長時間才能完成,但我可以將其作為一項作業運行而不會用完空間,也不會一直讓我的機器保持打開狀態。有沒有人做過類似的事情?任何幫助表示贊賞!
uj5u.com熱心網友回復:
如果您不能(或不想)在將它們發送到 S3 之前一次下載所有檔案,那么您需要一次下載一個。
此外,從那里開始,您需要構建要下載的檔案串列,然后處理它們,將一個檔案傳輸到本地計算機,然后將其發送到 S3。
一個非常簡單的版本看起來像這樣:
import pysftp
import stat
import boto3
import os
import json
# S3 bucket and prefix to upload to
target_bucket = "example-bucket"
target_prefix = ""
# Root FTP folder to sync
base_path = "./"
# Both base_path and target_prefix should end in a "/"
# Or, for the prefix, be empty for the root of the bucket
srv = pysftp.Connection(
host="server.com",
username="user1",
private_key="/mnt/results/sftpkey",
)
if os.path.isfile("all_files.json"):
# No need to cache files more than once. This lets us restart
# on a failure, though really we should be caching files in
# something more robust than just a json file
with open("all_files.json") as f:
all_files = json.load(f)
else:
# No local cache, go ahead and get the files
print("Need to get list of files...")
todo = [(base_path, target_prefix)]
all_files = []
while len(todo):
cur_dir, cur_prefix = todo.pop(0)
print("Listing " cur_dir)
for cur in srv.listdir_attr(cur_dir):
if stat.S_ISDIR(cur.st_mode):
# A directory, so walk into it
todo.append((cur_dir cur.filename "/", cur_prefix cur.filename "/"))
else:
# A file, just add it to our cache
all_files.append([cur_dir cur.filename, cur_prefix cur.filename])
# Save the cache out to disk
with open("all_files.json", "w") as f:
json.dump(all_files, f)
# And now, for every file in the cache, download it
# and turn around and upload it to S3
s3 = boto3.client('s3')
while len(all_files):
ftp_file, s3_name = all_files.pop(0)
print("Downloading " ftp_file)
srv.get(ftp_file, "_temp_")
print("Uploading " s3_name)
s3.upload_file("_temp_", target_bucket, s3_name)
# Clean up, and update the cache with one less file
os.unlink("_temp_")
with open("all_files.json", "w") as f:
json.dump(all_files, f)
srv.close()
錯誤檢查和速度改進顯然是可能的。
uj5u.com熱心網友回復:
您必須逐個檔案地執行此操作。
從這里的遞回下載代碼開始:
來自 Linux 的 Python pysftp get_r 在 Linux 上可以正常作業,但在 Windows 上不行
每次之后sftp.get,執行 S3 上傳并洗掉檔案。
實際上,您甚至可以將檔案從 SFTP 復制到 S#,而無需在本地存盤檔案:
Transfer file from SFTP to S3 using Paramiko
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/435113.html
