繁体   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