Moving an FTP List

I am trying to get the name of all directories from an FTP server and store them hierarchically in a multidimensional list or dict

So, for example, a server that contains the following structure:

/www/
    mysite.com
        images
            png
            jpg

at the end of the script, give me a list, for example

['/www/'
  ['mysite.com'
    ['images'
      ['png'],
      ['jpg']
    ]
  ]
]

I tried using a recursive function: def traverse (dir): FTP.dir (dir, traverse)

FTP.dir returns strings in this format:

drwxr-xr-x    5 leavesc1 leavesc1     4096 Nov 29 20:52 mysite.com

so the line [56:] will give me only the directory name (mysite.com). I use this in a recursive function.

But I can’t make it work. I tried many different approaches and can't make it work. There are also many FTP errors (either the directory cannot be found - this is a logical problem, and sometimes unexpected errors returned by a server that does not leave a log, and I can’t debug it)

: FTP-?

+3
5

. , CWD , , , . , LIST, .

import ftplib

def traverse(ftp, depth=0):
    """
    return a recursive listing of an ftp server contents (starting
    from the current directory)

    listing is returned as a recursive dictionary, where each key
    contains a contents of the subdirectory or None if it corresponds
    to a file.

    @param ftp: ftplib.FTP object
    """
    if depth > 10:
        return ['depth > 10']
    level = {}
    for entry in (path for path in ftp.nlst() if path not in ('.', '..')):
        try:
            ftp.cwd(entry)
            level[entry] = traverse(ftp, depth+1)
            ftp.cwd('..')
        except ftplib.error_perm:
            level[entry] = None
    return level

def main():
    ftp = ftplib.FTP("localhost")
    ftp.connect()
    ftp.login()
    ftp.set_pasv(True)

    print traverse(ftp)

if __name__ == '__main__':
    main()
+7

Python 3 script, . , cwd(). , , , . .

import ftplib
import sys

def ftp_walk(ftp, dir):
    dirs = []
    nondirs = []
    for item in ftp.mlsd(dir):
        if item[1]['type'] == 'dir':
            dirs.append(item[0])
        else:
            nondirs.append(item[0])
    if nondirs:
        print()
        print('{}:'.format(dir))
        print('\n'.join(sorted(nondirs)))
    else:
        # print(dir, 'is empty')
        pass
    for subdir in sorted(dirs):
        ftp_walk(ftp, '{}/{}'.format(dir, subdir))

ftp = ftplib.FTP()
ftp.connect(sys.argv[1], int(sys.argv[2]))
ftp.login(sys.argv[4], sys.argv[5])
ftp_walk(ftp, sys.argv[3])
+3

, " " , , " ".

, .

" " , FTP- (, , 7 ...).

+2

MLSD, " " .

+2

Python, :

http://docs.python.org/library/os.path.html (os.path.walk)

If you already have a good module for this, do not reinvent the wheel. I can’t believe that the message, which is two places higher, received two takeoffs, in any case, I like it.

-3
source

Source: https://habr.com/ru/post/1724847/


All Articles