使用Paramiko将文件从一个目录移动到另一个目录

10
我有一个脚本,用于在SFTP服务器上创建一个临时目录,并在传输完成后将文件放入该目录中,但我需要将文件从/tmp移回根目录/。使用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")
3个回答

20

1

我建议还要有一些保障措施。有时候在特定情况下(目标文件已存在或者要移动的文件不存在),库会抛出一个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)

-2

由于您已经导入了os库,请使用以下代码:

os.path.join(path, filename) 

为了获取正确的绝对路径并避免使用类似上面的通配符连接符处理重复或缺少的 / :
即:
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库中的rename函数,我可以远程移动文件。

你不能在SFTP路径中使用os.path.join。SFTP始终使用正斜杠作为路径分隔符,而os.path.join使用本地系统的路径分隔符(在Windows中将是反斜杠)。你的代码会引入与pysftp模块相同的问题:Python pysftp put_r在Windows上无法工作 - Martin Prikryl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接