我有一个脚本,可以在SFTP服务器上创建和tmp目录,然后/tmp
在传输完成后将文件放入其中,但是我需要将文件从/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")
使用sftp.rename
:
sftp.rename(remotePath+'/tmp/'+fileName, remotePath+fileName)
请注意,如果源目录和目标目录位于不同的文件系统上,则某些SFTP服务器会使请求失败。
如果需要将文件集从一个文件夹移动到另一个文件夹,请参见:
在Python中将所有文件从一个SFTP文件夹归档到另一个文件夹
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句