点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # -*- encoding: utf8 -*-
  3. # Mr.Wang

  4. import os
  5. import sys
  6. import ftplib
  7. import time

  8. mytime = time.strftime('%Y%m%d',time.localtime(time.time() - 24*60*60))

  9. class FTPSync(object):
  10.     def __init__(self):
  11.         self.conn = ftplib.FTP('XXX.XXX.XXX.XXX', 'user', 'password')
  12.         self.conn.cwd('/') # 远端FTP目录
  13.         os.chdir('/data/ftp/') # 本地下载目录
  14.     def get_dirs_files(self):
  15.         u''' 得到当前目录和文件, 放入dir_res列表 '''
  16.         dir_res = []
  17.         self.conn.dir('.', dir_res.append)
  18.         files = [f.split(None, 8)[-1] for f in dir_res if f.startswith('-')]
  19.         dirs = [f.split(None, 8)[-1] for f in dir_res if f.startswith('d')]
  20.         return (files, dirs)
  21.     def walk(self, next_dir):
  22.         print 'Walking to', next_dir
  23.         self.conn.cwd(next_dir)
  24.         try:
  25.             os.mkdir(next_dir)
  26.         except OSError:
  27.             pass
  28.         os.chdir(next_dir)
  29.         ftp_curr_dir = self.conn.pwd()
  30.         local_curr_dir = os.getcwd()
  31.         files, dirs = self.get_dirs_files()
  32.         print "FILES: ", files
  33.         print "DIRS: ", dirs
  34.         for f in files:
  35.                         if mytime in f:
  36.                                 print next_dir, ':', f
  37.                                 outf = open(f, 'wb')
  38.                                 try:
  39.                                         self.conn.retrbinary('RETR %s' % f, outf.write)
  40.                                 finally:
  41.                                         outf.close()
  42.         for d in dirs:
  43.             os.chdir(local_curr_dir)
  44.             self.conn.cwd(ftp_curr_dir)
  45.             self.walk(d)
  46.     def run(self):
  47.         self.walk('.')
  48. def main():
  49.     f = FTPSync()
  50.     f.run()
  51. if __name__ == '__main__':
  52.     main()

10-02 07:25