python - Traversing FTP listing -
I am trying to get names of all the directories from an FTP server and they have a multidimensional list or terminology
< P> For example, a server with the following structure: / www / mysite.com Images png jpg
at the end of the script, give me a list >> I have tried to use a recursive function such as: DefTrurs (DIR): FTP.dir (dir, traverse)
< P> FTP.dir return line in this format: drwxr-xr-x 5 pagesc1 leavesc1 4096 29 November 20:52 mysite.com
By doing the line [56:] just give me the directory name (mysite.com) I use it in its recurring function.
But I can not get it to work. I've tried many different ways and it can not be found to work as well as lots of FTP errors (or Then the directory can not be found - which is a logical issue, and sometimes unexpected errors are returned by the server, which does not leave a log and I can not debug it)
Bottom line question: How to get a hierarchical directory from FTP server?
There is a simple and slow implementation here, it is slow because it tries to CWD in every directory entry , To determine whether it is a directory or file, but it works. Anyone can optimize it by parsing the LIST command output, but it is strongly dependent on server-implementation.
import ftplib def traverse (ftp, depth = 0): "" A recursive list is returned back to the FTP server content (starting from the current directory) as the recursive dictionary , Where each key contains the contents of the subdirectory or none if it matches the file. @user FTP: ftplib.FTP object "" if depth and gt; 10: return ['depth' ('. ',' .. ')): Try: ftp.cwd (entry) level [entry] = path for transfers (login) (ftp Path to path in .nlst () (except for ftp, depth + 1) ftplib.error_perm ('..'): level [entry] = any return level def main (): ftp = ftplib.FTP ("localhost ") Ftp.connect () ftp .login () ftp.set_pasv (True) Print Travers (FTP) if __name__ == '__main__': main ()
Comments
Post a Comment