簡體   English   中英

使用 Paramiko 將文件從一個目錄移動到另一個目錄

[英]Move files from one directory to another with Paramiko

我有一個腳本,它在 SFTP 服務器上創建 tmp 目錄,然后在傳輸完成后將文件放在所述/tmp中,但是我需要將文件從/tmp移回一個目錄到 root / 使用 Paramiko 如何將文件從一個遠程目錄移動到另一個?

步驟指南:

本地文件-----> 遠程臨時目錄----> 遠程根目錄

如果需要,請使用以下代碼:

#!/usr/bin/python

# --------------------------------------------------------------------
#import libraries
# --------------------------------------------------------------------
import paramiko as PM
import os
import datetime

# --------------------------------------------------------------------
# Global Variables
# --------------------------------------------------------------------

host = 'host IP address'
port = 22
username = 'Username'
password = '*********'

# Variable Paths

localPath = '/shares/MILKLINK/fromML'
remotePath = '/'
logPath = '/shares/MILKLINK/logs/PPcfg02.log'
SRCfiles = '/shares/MILKLINK/Milklink.cpy'

# --------------------------------------------------------------------
#  Create LOG FILE
# --------------------------------------------------------------------

log = open(logPath, 'a')
log.write(datetime.datetime.now().isoformat()+'\n')

# Creating lockfile

if(os.path.isfile('LockSFTP')):
    log.write("LOCK FILE STILL EXISTS!")
    quit()
else:    
    os.system(">LockSFTP")

# --------------------------------------------------------------------
# Remove all files from /formML/ 
# --------------------------------------------------------------------

fileList = os.listdir(localPath)
for fileName in fileList:
    try:
        os.remove(localPath+"/"+fileName)
    except OSError:
        log.write("%s could not be deleted\n" % fileName)

# --------------------------------------------------------------------
#  Create SFTP CONNECTION
# --------------------------------------------------------------------

log.write("Starting Connection...\n")
# SSH connection
ssh_Connection = PM.Transport((host, port))
ssh_Connection.connect(username = username, password = password)

# Creaat SFTP CLIENT SERVICES
sftp = PM.SFTPClient.from_transport(ssh_Connection) 

log.write("Connection Established...\n")

remoteList = sftp.listdir(remotePath)
fileList = os.listdir(SRCfiles)
try:
    sftp.chdir(remotePath+'/tmp')
except IOError:
    sftp.mkdir(remotePath+'/tmp')
    sftp.chdir(remotePath+'/tmp')

for fileName in fileList:
    if 'comphaulier.asc' not in remoteList:
        if 'Last' in fileName:
            continue
        else:
            sftp.put(SRCfiles+'/'+fileName, remotePath+'/tmp/'+fileName)

        log.write(fileName+" Transferred\n")
    else:
        log.write("Files Still Exist\n")
        log.close()
        quit()

checkList = sftp.listdir(remotePath)

if len(checkList) == 7:
    sftp.put(SRCfiles+'/LastFile.lst', remotePath+'/LastFile.lst')
    log.write("LastFile.lst Transferred\n")
else:
    log.write("Not all files transferred!!!\n")
    quit()

sftp.close()
ssh_Connection.close()

os.system("rm LockSFTP")

使用sftp.rename

sftp.rename(remotePath+'/tmp/'+fileName, remotePath+fileName)

請注意,如果源目錄和目標目錄位於不同的文件系統上,則某些 SFTP 服務器會使請求失敗。


如果您需要將一組文件從一個文件夾移動到另一個文件夾,請參閱:
在 Python 中將所有文件從一個 SFTP 文件夾存檔到另一個文件夾

我建議也有一些保障措施。 有時庫會在某些情況下引發 IOError (目標文件已經存在或要移動的文件不存在)。 我假設你有一個 sftp 客戶端sftp_client

def move_file(self, source, destination):
    destination_file_exists = __file_exists(destination)
    source_file_exists = __file_exists(source)
    if destination_file_exists:
        # handle the condition accordingly
        print(f"destination file {destination} already exists")
    else:
        if source_file_exists:
            sftp_client.rename(source, destination)
        else:
            # handle the condition accordingly
            print(f"source file {source} does not exist")

def __file_exists(file_path):
    try:
        sftp_client.stat(file_path)
        return True
    except FileNotFoundError as e:
        return False
    except Exception as e:
        print(e)

因為您已經導入了 os 庫,請使用:

os.path.join(path, filename) 

要獲得正確的絕對路徑並避免處理重復或缺少 / 通過使用像上面這樣的野生連接:

IE

f_w_current_path = os.path.join(current_path, f.filename)
f_w_temporary_path = os.path.join(temporary_path, f.filename)
sftp.rename(f_w_current_path, f_w_temporary_path)

使用重命名通過 paramiko 庫遠程移動文件,它對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM