This article mainly introduces the PythonFTP operation class, which enables automatic download, automatic upload, and recursive directory operations. For more information, see
The code is as follows:
#! /Usr/bin/py2
#-*-Coding: UTF-8 -*-
# Encoding = UTF-8
'''''
Ftp automatic download, automatic upload script, Recursive directory operations
'''
From ftplib import FTP
Import OS, sys, string, datetime, time
Import socket
Class FtpClient:
Def _ init _ (self, host, user, passwd, remotedir, port = 21 ):
Self. hostaddr = host
Self. username = user
Self. password = passwd
Self. remotedir = remotedir
Self. port = port
Self. ftp = FTP ()
Self. file_list = []
Def _ del _ (self ):
Self. ftp. close ()
Def login (self ):
Ftp = self. ftp
Try:
Timeout = 60
Socket. setdefatimetimeout (timeout)
Ftp. set_pasv (True)
Ftp. connect (self. hostaddr, self. port)
Print 'connect Success % s' % (self. hostaddr)
Ftp. login (self. username, self. password)
Print 'login Success % s' % (self. hostaddr)
Debug_print (ftp. getwelcome ())
Failed T Exception:
Deal_error ("Connect Error or Login Error ")
Try:
Ftp. cwd (self. remotedir)
Except t (Exception ):
Deal_error ('change Directory error ')
Def is_same_size (self, localfile, remotefile ):
Try:
Remotefile_size = self. ftp. size (remotefile)
Except t:
Remotefile_size =-1
Try:
Localfile_size = OS. path. getsize (localfile)
Except t:
Localfile_size =-1
Debug_print ('lo: % d re: % d' % (localfile_size, remotefile_size ),)
If remotefile_size = localfile_size:
Return 1
Else:
Return 0
Def download_file (self, localfile, remotefile ):
If self. is_same_size (localfile, remotefile ):
Return
Else:
Pass
File_handler = open (localfile, 'WB ')
Self. ftp. retrbinary ('retr % s' % (remotefile), file_handler.write)
File_handler.close ()
Def download_files (self, localdir = './', remotedir = './'):
Try:
Self. ftp. cwd (remotedir)
Except t:
Return
If not OS. path. isdir (localdir ):
OS. makedirs (localdir)
Self. file_list = []
Self. ftp. dir (self. get_file_list)
Remotenames = self. file_list
For item in remotenames:
Filetype = item [0]
Filename = item [1]
Local = OS. path. join (localdir, filename)
If filetype = 'd ':
Self. download_files (local, filename)
Elif filetype = '-':
Self. download_file (local, filename)
Self. ftp. cwd ('..')
Def upload_file (self, localfile, remotefile ):
If not OS. path. isfile (localfile ):
Return
If self. is_same_size (localfile, remotefile ):
Return
File_handler = open (localfile, 'RB ')
Self. ftp. storbinary ('stor % s' % remotefile, file_handler)
File_handler.close ()
Def upload_files (self, localdir = './', remotedir = './'):
If not OS. path. isdir (localdir ):
Return
Localnames = OS. listdir (localdir)
Self. ftp. cwd (remotedir)
For item in localnames:
Src = OS. path. join (localdir, item)
If OS. path. isdir (src ):
Try:
Self. ftp. mkd (item)
Except t:
Debug_print ('directory Exists % s' % item)
Self. upload_files (src, item)
Else:
Self. upload_file (src, item)
Self. ftp. cwd ('..')
Def mkdir (self, remotedir = './'):
Try:
Self. ftp. mkd (remotedir)
Except t:
Debug_print ('directory Exists % s' % remotedir)
Def get_file_list (self, line ):
Ret_arr = []
File_arr = self. get_filename (line)
If file_arr [1] not in ['.', '...']:
Self. file_list.append (file_arr)
Def get_filename (self, line ):
Pos = line. rfind (':')
While (line [pos]! = ''):
Pos + = 1
While (line [pos] = ''):
Pos + = 1
File_arr = [line [0], line [pos:]
Return file_arr
Def debug_print (str ):
Print (str)
Def deal_error (e ):
Timenow = time. localtime ()
Datenow = time. strftime ('% Y-% m-% d', timenow)
Logstr = '% s Error: % s' % (datenow, e)
Debug_print (logstr)
File. write (logstr)
Sys. exit ()