分享一个Python实现 的 FTP操作类,功能包括:自动下载、自动上传,并可以递归目录操作等。
个人感觉很不错,强大且实用的python ftp类。

完整代码:
  1. #!/usr/bin/py2
  2. # -*- coding: utf-8 -*-
  3. #encoding=utf-8
    # www.jbxue.com
  4. '''''
  5.     ftp自动下载、自动上传脚本,可以递归目录操作
  6. '''
  7. from ftplib import FTP
  8. import os, sys, string, datetime, time
  9. import socket
  10. class FtpClient:
  11.     def __init__(self, host, user, passwd, remotedir, port=21):
  12.         self.hostaddr = host
  13.         self.username = user
  14.         self.password = passwd
  15.         self.remotedir = remotedir
  16.         self.port = port
  17.         self.ftp = FTP()
  18.         self.file_list = []
  19.     def __del__(self):
  20.         self.ftp.close()
  21.     def login(self):
  22.         ftp = self.ftp
  23.         try:
  24.             timeout = 60
  25.             socket.setdefaulttimeout(timeout)
  26.             ftp.set_pasv(True)
  27.             ftp.connect(self.hostaddr, self.port)
  28.             print 'Connect Success %s' %(self.hostaddr)
  29.             ftp.login(self.username, self.password)
  30.             print 'Login Success %s' %(self.hostaddr)
  31.             debug_print(ftp.getwelcome())
  32.         except Exception:
  33.             deal_error("Connect Error or Login Error")
  34.         try:
  35.             ftp.cwd(self.remotedir)
  36.         except(Exception):
  37.             deal_error('Change Directory Error')
  38.     def is_same_size(self, localfile, remotefile):
  39.         try:
  40.             remotefile_size = self.ftp.size(remotefile)
  41.         except:
  42.             remotefile_size = -1
  43.         try:
  44.             localfile_size = os.path.getsize(localfile)
  45.         except:
  46.             localfile_size = -1
  47.         debug_print('lo:%d re:%d' %(localfile_size, remotefile_size),)
  48.         if remotefile_size == localfile_size:
  49.             return 1
  50.         else:
  51.             return 0
  52.     def download_file(self, localfile, remotefile):
  53.         if self.is_same_size(localfile, remotefile):
  54.             return
  55.         else:
  56.             pass
  57.         file_handler = open(localfile, 'wb')
  58.         self.ftp.retrbinary('RETR %s'%(remotefile), file_handler.write)
  59.         file_handler.close()
  60.     def download_files(self, localdir='./', remotedir='./'):
  61.         try:
  62.             self.ftp.cwd(remotedir)
  63.         except:
  64.             return
  65.         if not os.path.isdir(localdir):
  66.             os.makedirs(localdir)
  67.         self.file_list = []
  68.         self.ftp.dir(self.get_file_list)
  69.         remotenames = self.file_list
  70.         for item in remotenames:
  71.             filetype = item[0]
  72.             filename = item[1]
  73.             local = os.path.join(localdir, filename)
  74.             if filetype == 'd':
  75.                 self.download_files(local, filename)
  76.             elif filetype == '-':
  77.                 self.download_file(local, filename)
  78.         self.ftp.cwd('..')
  79.     def upload_file(self, localfile, remotefile):
  80.         if not os.path.isfile(localfile):
  81.             return
  82.         if self.is_same_size(localfile, remotefile):
  83.             return 
  84.         file_handler = open(localfile, 'rb')
  85.         self.ftp.storbinary('STOR %s' %remotefile, file_handler)
  86.         file_handler.close()  www.jbxue.com
  87.     def upload_files(self, localdir='./', remotedir = './'):
  88.         if not os.path.isdir(localdir):
  89.             return
  90.         localnames = os.listdir(localdir)
  91.         self.ftp.cwd(remotedir)
  92.         for item in localnames:
  93.             src = os.path.join(localdir, item)
  94.             if os.path.isdir(src):
  95.                 try:
  96.                     self.ftp.mkd(item)
  97.                 except:
  98.                     debug_print('Directory Exists %s' %item)
  99.                 self.upload_files(src, item)
  100.             else:
  101.                 self.upload_file(src, item)
  102.         self.ftp.cwd('..')
  103.     def mkdir(self, remotedir='./'):
  104.         try:
  105.             self.ftp.mkd(remotedir)
  106.         except:
  107.             debug_print('Directory Exists %s' %remotedir)
  108.     def get_file_list(self, line):
  109.         ret_arr = []
  110.         file_arr = self.get_filename(line)
  111.         if file_arr[1] not in ['.', '..']:
  112.             self.file_list.append(file_arr)
  113.     def get_filename(self, line):
  114.         pos = line.rfind(':')
  115.         while(line[pos] != ' '):
  116.             pos += 1
  117.         while(line[pos] == ' '):
  118.             pos += 1
  119.         file_arr = [line[0], line[pos:]]
  120.         return file_arr
  121. def debug_print(str):
  122.     print (str)
  123. def deal_error(e):
  124.     timenow = time.localtime()
  125.     datenow = time.strftime('%Y-%m-%d', timenow)
  126.     logstr = '%s Error: %s' %(datenow, e)
  127.     debug_print(logstr)
  128.     file.write(logstr)
  129.     sys.exit()
10-02 07:20