# coding=utf-8
import os
import sys
import ftplib
reload(sys)
sys.setdefaultencoding('utf-8')

class myFtp:
    ftp = ftplib.FTP()

    def __init__(self, host, port):
        self.ftp.connect(host, port)

    def Login(self, user, passwd):
        self.ftp.login(user, passwd)
        print(self.ftp.welcome)

    # 下载当个文件
    def DownLoadFile(self, LocalFile, RemoteFile):
        file_handler = open(LocalFile, 'wb')
        print(file_handler)
        #接收服务器上文件并写入本地文件
        self.ftp.retrbinary('RETR ' + RemoteFile, file_handler.write)
        file_handler.close()
        return True

    # 下载整个目录下的文件
    def DownLoadFileTree(self, LocalDir,RemoteDir):
        print("remoteDir:", RemoteDir)
        if not os.path.exists(LocalDir):
            os.makedirs(LocalDir)
        self.ftp.cwd(RemoteDir)
        RemoteNames = self.ftp.nlst()
        print("RemoteNames", RemoteNames)
        for file in RemoteNames:
            if file=="." or file=="..":
                continue
            Local = os.path.join(LocalDir, file)
            print(self.ftp.nlst(file))
            if file.find(".") == -1:
                if not os.path.exists(Local):
                    os.makedirs(Local)
                self.DownLoadFileTree(Local, file)
            else:
                self.DownLoadFile(Local, file)
        self.ftp.cwd("..")
        return

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


if __name__ == "__main__":
    ftp = myFtp('192.0.0.0',21)
    ftp.Login('zh', '1111111')
    ftp.DownLoadFileTree(r'C:\Users\bb\Desktop\mm','xxxx/download')
    ftp.close()
    print("ok!")

 

发表评论

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