Python FTP operation class code sharing _python

Source: Internet
Author: User

Copy Code code as follows:

#!/usr/bin/py2
#-*-Coding:utf-8-*-
#encoding =utf-8

'''''
FTP automatic download, automatic upload script, can be recursive directory operation
'''

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.setdefaulttimeout (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 ())
Except Exception:
Deal_error ("Connect Error or Login error")
Try
FTP.CWD (Self.remotedir)
Except (Exception):
Deal_error (' Change Directory error ')

def is_same_size (self, LocalFile, remotefile):
Try
Remotefile_size = Self.ftp.size (remotefile)
Except
Remotefile_size =-1
Try
Localfile_size = Os.path.getsize (LocalFile)
Except
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
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
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
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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.