使用ftplib模块,实现列出ftp上指定目录下的所有文件,包含子目录

# coding: utf-8
# for python35+

import os
import ftplib

class FtpTools(object):
    def __init__(self, host, username, password):
        self.dir_sum = 0
        self.res_sum = 0
        self.size_sum = 0
        self.host = host
        self.username = username
        self.password = password
        self.ftp = ftplib.FTP(self.host)
        self.ftp.login(self.username, self.password)
        self.ftp.encoding='utf-8'

    def filelist(self, ftp_dir):
        self.ftp.cwd(ftp_dir)
        for name, facts in self.ftp.mlsd(".",["type", "size"]):
            if facts["type"] == "dir":
                if self.ftp.pwd().endswith('/'):
                    dir_cwd = self.ftp.pwd() + name
                else:
                    dir_cwd = self.ftp.pwd() + os.sep + name
                try:
                    self.dir_sum += 1
                    self.filelist(dir_cwd)
                    self.ftp.cwd('..')
                except:
                    pass
            else:
                self.res_sum += 1
                self.size_sum += int(facts["size"])
                if self.ftp.pwd().endswith('/'):
                    res_path = self.ftp.pwd() + name
                else:
                    res_path = self.ftp.pwd() + os.sep + name
                print (res_path)
        
    def count(self):
        count_msg = f"文件夹: {self.dir_sum}, 文件数: {self.res_sum}, 总大小: {self.size_sum/1024/1024}/MB"
        print (count_msg)

    def close():
        self.ftp.quit()


if __name__ == "__main__":
    host = "192.168.1.111"
    username = "test"
    password = "test.com"

    ftptools = FtpTools(host, username, password)
    ftptools.filelist('/')
    ftptools.count()

结果

(py3) [root@mongodb ftptools]# python ftptools.py 
/bitnami-redmine-4.0.2-0-linux-x64-installer.run
/mysite-master/blogApp/admin.py
/mysite-master/blogApp/apps.py
/mysite-master/blogApp/models.py
/mysite-master/blogApp/serializers.py
/mysite-master/blogApp/tests.py
/mysite-master/blogApp/urls.py
/mysite-master/blogApp/views.py
/mysite-master/manage.py
/mysite-master/mysite/settings.py
/mysite-master/mysite/urls.py
/mysite-master/mysite/wsgi.py
/mysite-master/README.md
/mysite-master/requirments.txt
/mysite-master/同步.bat
/mysite-master/启动.bat
...
/procexp64.exe
/TeamViewer_Setup.exe
文件夹: 10, 文件数: 56, 总大小: 240.06631660461426/MB

发表评论

电子邮件地址不会被公开。 必填项已用*标注