Skip to content
mar 27 / David Regnier

Implémentation d’une classe FTP en Python

Voici une classe de base FTP en Python (qui marche derrière un proxy si besoin):

Prérequis:

#    Mode: Python tab-width: 4
#    Id: helper_ftp.py
#    Author: David REGNIER
#    Description: Misc functions used by main class
#
# ======================================================================
# Copyright 2014 by David REGNIER
#
#                         All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in all
# copies and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name David
# REGNIER not be used in advertising or publicity pertaining to
# distribution of the software without specific, written prior
# permission.
# ======================================================================

import os, sys
from ftplib import FTP
from configobj import ConfigObj # We need configobj lib

# Init config variables
oConfig = ConfigObj('config.cfg')

"""Begin main class"""
class FTPSession(object):
    # Constructor
    def __init__(self, sFTPProxy, sFTPHost, sFTPUser, sFTPPassword, sLocalDir, sRemoteDir):
        self.sFTPProxy = sFTPProxy
        self.sFTPHost = sFTPHost
        self.sFTPUser = sFTPUser
        self.sFTPPassword = sFTPPassword
        self.sLocalDir = sLocalDir
        self.sRemoteDir = sRemoteDir

    # Begin initlogerror
    def initlogerror(self):
        try:
            sCurrentScriptFileName = os.path.basename(__file__)
            fSock = open(sCurrentScriptFileName[:-3] + '_error.log', 'w')
            sys.stderr = fSock
        except Exception, e:
            print str(e)
    # End initlogerror

    # Begin doftpsession
    def doftpsession(self):
        try:
            aFtpList = []

            # List files from folder
            def handlelistdir(line):
                # Create local folder if not exist
                if not os.path.exists(self.sLocalDir):
                    os.makedirs(self.sLocalDir)                

                # Get remote files list
                slineSplitted = line.split()
                aFtpList.append(slineSplitted[len(slineSplitted)-1])
            # End handlelistdir

            # Write block
            def handledownload(block):
                ofile.write(block)
            # End handledownload

            # Begin main
            ftp = FTP(self.sFTPProxy) # Open FTP connection on proxy if needed
            ftp.login(self.sFTPUser + '@' + self.sFTPHost + ':21', self.sFTPPassword)
            print ftp.getwelcome()
            ftp.retrlines('LIST %s' % self.sRemoteDir, handlelistdir) # List remote files
            sLocalListDir = os.listdir(os.getcwd()+'/%s'  % self.sLocalDir) # List local files
            for el in aFtpList:
                # Download only if not exist in local folder
                # You can define any file type if you need a file filter, sample "zip"
                if (el not in sLocalListDir) & ('zip' in el):
                    ofile = open(os.getcwd()+'/%s/%s'  % (self.sLocalDir, el), 'wb')
                    print 'getting from ftp:', el, '...'
                    ftp.retrbinary('RETR %s/%s' %(self.sRemoteDir, el), handledownload)
                    ofile.close()
            ftp.quit() # Close FTP connection
            # End main
        except Exception, e:
            print str(e)
    # End doftpsession
"""End main class"""

Appel de la classe Python:

# Sample call
oFTP = FTPSession(
    oConfig['ftp_section']['ftp_proxy'],
    oConfig['ftp_section']['ftp_host'],
    oConfig['ftp_section']['ftp_user'],
    oConfig['ftp_section']['ftp_password'],
    oConfig['ftp_section']['ftp_local_dir'],
    oConfig['ftp_section']['ftp_remote_dir']
)
oFTP.initlogerror()
oFTP.doftpsession()

Voici le fichier de config.cfg utilisé pour mon script:


[ftp_section]
ftp_proxy = my.proxy
ftp_host = my.host.fr
ftp_user = user
ftp_password = password
ftp_local_dir = local_dir
ftp_remote_dir = remote_dir
Vous devez modifier cette classe en fonction de vos besoins, cette classe marche derrière un proxy si besoin
Laisser un commentaire


5 × = 25