如何使用Python脚本从FTP服务器删除超过7天的文件?

2024-04-26 14:51:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个Python脚本,它允许我在文件到达一定年龄后从FTP服务器上删除文件。我准备了下面的scpt,但它抛出了错误消息:WindowsError: [Error 3] The system cannot find the path specified: '/test123/*.*'

有人知道如何解决这个问题吗?提前谢谢你!

import os, time
from ftplib import FTP

ftp = FTP('127.0.0.1')
print "Automated FTP Maintainance"
print 'Logging in.'
ftp.login('admin', 'admin')

# This is the directory that we want to go to
path = 'test123'
print 'Changing to:' + path
ftp.cwd(path)
files = ftp.retrlines('LIST')
print 'List of Files:' + files 
#--everything works fine until here!...

#--The Logic which shall delete the files after the are 7 days old--
now = time.time()
for f in os.listdir(path):
  if os.stat(f).st_mtime < now - 7 * 86400:
    if os.path.isfile(f):
        os.remove(os.path.join(path, f))
except:
    exit ("Cannot delete files")

print 'Closing FTP connection'
ftp.close()

Tags: 文件thetopathinimportadmintime
3条回答

好的。假设您的FTP服务器支持MLSD命令,使用以下代码创建一个模块(这是我用于将远程FTP站点与本地目录同步的脚本中的代码):

模块代码

# for python ≥ 2.6
import sys, os, time, ftplib
import collections
FTPDir= collections.namedtuple("FTPDir", "name size mtime tree")
FTPFile= collections.namedtuple("FTPFile", "name size mtime")

class FTPDirectory(object):
    def __init__(self, path='.'):
        self.dirs= []
        self.files= []
        self.path= path

    def getdata(self, ftpobj):
        ftpobj.retrlines('MLSD', self.addline)

    def addline(self, line):
        data, _, name= line.partition('; ')
        fields= data.split(';')
        for field in fields:
            field_name, _, field_value= field.partition('=')
            if field_name == 'type':
                target= self.dirs if field_value == 'dir' else self.files
            elif field_name in ('sizd', 'size'):
                size= int(field_value)
            elif field_name == 'modify':
                mtime= time.mktime(time.strptime(field_value, "%Y%m%d%H%M%S"))
        if target is self.files:
            target.append(FTPFile(name, size, mtime))
        else:
            target.append(FTPDir(name, size, mtime, self.__class__(os.path.join(self.path, name))))

    def walk(self):
        for ftpfile in self.files:
            yield self.path, ftpfile
        for ftpdir in self.dirs:
            for path, ftpfile in ftpdir.tree.walk():
                yield path, ftpfile

class FTPTree(FTPDirectory):
    def getdata(self, ftpobj):
        super(FTPTree, self).getdata(ftpobj)
        for dirname in self.dirs:
            ftpobj.cwd(dirname.name)
            dirname.tree.getdata(ftpobj)
            ftpobj.cwd('..')

单目录案例

如果要处理目录的文件,可以:

import ftplib, time

quite_old= time.time() - 7*86400 # seven days

site= ftplib.FTP(hostname, username, password)
site.cwd(the_directory_to_work_on) # if it's '.', you can skip this line
folder= FTPDirectory()
folder.getdata(site) # get the filenames
for path, ftpfile in folder.walk():
    if ftpfile.mtime < quite_old:
        site.delete(ftpfile.name)

这应该是你想要的。

目录及其子目录

现在,如果这应该递归地工作,那么您必须在“single directory case”的代码中进行以下两个更改:

folder= FTPTree()

以及

site.delete(os.path.join(path, ftpfile.name))

可能的警告

我使用过的服务器在STORDELE命令中的相对路径没有任何问题,因此site.delete使用相对路径也可以工作。如果FTP服务器需要无路径文件名,则应首先.cwd到提供的path,再.delete到普通的ftpfile.name,然后.cwd返回到基文件夹。

好吧,与其进一步分析你发布的代码,这里有一个例子可以让你走上正轨。

from ftplib import FTP
import re

pattern = r'.* ([A-Z|a-z].. .. .....) (.*)'

def callback(line):
    found = re.match(pattern, line)
    if (found is not None):
        print found.groups()

ftp = FTP('myserver.wherever.com')
ftp.login('elvis','presley')
ftp.cwd('testing123')
ftp.retrlines('LIST',callback)

ftp.close()
del ftp

运行它,你会得到类似这样的输出,这应该是你努力实现目标的开始。要完成它,您需要将第一个结果解析为datetime,将其与“now”进行比较,如果远程文件太旧,则使用ftp.delete()删除它。

>>> 
('May 16 13:47', 'Thumbs.db')
('Feb 16 17:47', 'docs')
('Feb 23  2007', 'marvin')
('May 08  2009', 'notes')
('Aug 04  2009', 'other')
('Feb 11 18:24', 'ppp.xml')
('Jan 20  2010', 'reports')
('Oct 10  2005', 'transition')
>>> 

我不得不这样做,花了一段时间,以为我可以节省一些时间在这里。我们使用安装了ftputil模块的python:

#! /usr/bin/python
import time
import ftputil
host = ftputil.FTPHost('ftphost.com', 'username', 'password')
mypath = 'ftp_dir'
now = time.time()
host.chdir(mypath)
names = host.listdir(host.curdir)
for name in names:
    if host.path.getmtime(name) < (now - (7 * 86400)):
      if host.path.isfile(name):
         host.remove(name)


print 'Closing FTP connection'
host.close()

相关问题 更多 >