遍历FTP清单

遍历FTP清单,第1张

遍历FTP清单

这是一个幼稚且缓慢的实现。这很慢,因为它尝试CWD到每个目录条目以确定它是目录还是文件,但这是可行的。可以通过解析LIST命令输出来优化它,但这在很大程度上取决于服务器实现。

import ftplibdef 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 leveldef main():    ftp = ftplib.FTP("localhost")    ftp.connect()    ftp.login()    ftp.set_pasv(True)    print traverse(ftp)if __name__ == '__main__':    main()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5674629.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存