Downloading a directory tree with ftplib

Anthony Lemmer picture Anthony Lemmer · Apr 9, 2010 · Viewed 24.8k times · Source

This will not download the contents of sub-directories; how can I do so?

import ftplib
import configparser
import os

directories = []

def add_directory(line):
 if line.startswith('d'):
  bits = line.split()
  dirname = bits[8]
  directories.append(dirname)

def makeDir(archiveTo):
 for dir in directories:
  newDir = os.path.join(archiveTo, dir)
  if os.path.isdir(newDir) == True:
   print("Directory \"" + dir + "\" already exists!")
  else:
   os.mkdir(newDir)

def getFiles(archiveTo, ftp):
 files = ftp.nlst()
 for filename in files:
  try:
   directories.index(filename)
  except:
   ftp.retrbinary('RETR %s' % filename, open(os.path.join(archiveTo, filename), 'wb').write)

def runBackups():

 #Load INI
 filename = 'connections.ini'
 config = configparser.SafeConfigParser()
 config.read(filename)

 connections = config.sections()
 i = 0

 while i < len(connections):
  #Load Settings
  uri = config.get(connections[i], "uri")
  username = config.get(connections[i], "username")
  password = config.get(connections[i], "password")
  backupPath = config.get(connections[i], "backuppath")
  archiveTo = config.get(connections[i], "archiveto")

  #Start Back-ups
  ftp = ftplib.FTP(uri)
  ftp.login(username, password)
  ftp.cwd(backupPath)

  #Map Directory Tree
  ftp.retrlines('LIST', add_directory)

  #Make Directories Locally
  makeDir(archiveTo)

  #Gather Files
  getFiles(archiveTo, ftp)

  #End connection and increase counter.
  ftp.quit()
  i += 1

 print()
 print("Back-ups complete.")
 print()

Answer

jameh picture jameh · May 18, 2012

this should do the trick :)

import sys
import ftplib
import os
from ftplib import FTP
ftp=FTP("ftp address")
ftp.login("user","password")

def downloadFiles(path,destination):
#path & destination are str of the form "/dir/folder/something/"
#path should be the abs path to the root FOLDER of the file tree to download
    try:
        ftp.cwd(path)
        #clone path to destination
        os.chdir(destination)
        os.mkdir(destination[0:len(destination)-1]+path)
        print destination[0:len(destination)-1]+path+" built"
    except OSError:
        #folder already exists at destination
        pass
    except ftplib.error_perm:
        #invalid entry (ensure input form: "/dir/folder/something/")
        print "error: could not change to "+path
        sys.exit("ending session")

    #list children:
    filelist=ftp.nlst()

    for file in filelist:
        try:
            #this will check if file is folder:
            ftp.cwd(path+file+"/")
            #if so, explore it:
            downloadFiles(path+file+"/",destination)
        except ftplib.error_perm:
            #not a folder with accessible content
            #download & return
            os.chdir(destination[0:len(destination)-1]+path)
            #possibly need a permission exception catch:
            ftp.retrbinary("RETR "+file, open(os.path.join(destination,file),"wb").write)
            print file + " downloaded"
    return

source="/ftproot/folder_i_want/"
dest="/systemroot/where_i_want_it/"
downloadFiles(source,dest)