Copy codeThe Code is as follows: #-*-encoding: utf8 -*-
Import OS
Import sys
Import ftplib
Class FTPSync (object ):
Def _ init _ (self ):
Self. conn = ftplib. FTP ('10. 22.33.46 ', 'user', 'pass ')
Self. conn. cwd ('/') # remote FTP directory
OS. chdir ('/data/') # local download directory
Def get_dirs_files (self ):
U''' to get the current directory and file, and put it in the dir_res list '''
Dir_res = []
Self. conn. dir ('.', dir_res.append)
Files = [f. split (None, 8) [-1] for f in dir_res if f. startswith ('-')]
Dirs = [f. split (None, 8) [-1] for f in dir_res if f. startswith ('D')]
Return (files, dirs)
Def walk (self, next_dir ):
Print 'walking to', next_dir
Self. conn. cwd (next_dir)
Try:
OS. mkdir (next_dir)
Failed t OSError:
Pass
OS. chdir (next_dir)
Ftp_curr_dir = self. conn. pwd ()
Local_curr_dir = OS. getcwd ()
Files, dirs = self. get_dirs_files ()
Print "FILES:", files
Print "DIRS:", dirs
For f in files:
Print next_dir, ':', f
Outf = open (f, 'wb ')
Try:
Self. conn. retrbinary ('retr % s' % f, outf. write)
Finally:
Outf. close ()
For d in dirs:
OS. chdir (local_curr_dir)
Self. conn. cwd (ftp_curr_dir)
Self. walk (d)
Def run (self ):
Self. walk ('.')
Def main ():
F = FTPSync ()
F. run ()
If _ name _ = '_ main __':
Main ()