python通过FTP从远程服务器下载文件

前沿

如题,话不多说,直接上代码。

python实现

from ftplib import FTP
import os

class FTP_OP(object):
    def __init__(self, host, username, password, port):
        """
        初始化ftp
      :param host: ftp主机ip
      :param username: ftp用户名
      :param password: ftp密码
      :param port: ftp端口 (默认21)
      """
        self.host = host
        self.username = username
        self.password = password
        self.port = port

    def ftp_connect(self):
        """
        连接ftp
        :return:
        """
        ftp = FTP()
        ftp.set_debuglevel(1)  # 不开启调试模式
        ftp.connect(host=self.host, port=self.port)  # 连接ftp
        ftp.login(self.username, self.password)  # 登录ftp
        ftp.set_pasv(False)  # ftp有主动 被动模式 需要调整
        return ftp

    def download_file(self, ftp_file_path, dst_file_path):
        """
        从ftp下载文件到本地
        :param ftp_file_path: ftp下载文件路径
        :param dst_file_path: 本地存放路径
        :return:
        """
        buffer_size = 102400  # 默认是8192
        ftp = self.ftp_connect()
        print(ftp.getwelcome())  # 显示登录ftp信息
        dir_list = ftp.nlst(ftp_file_path)
        for dir_name in dir_list:
            print("file_name: " + dir_name)      # 日期列表
            dir1 = dst_file_path + dir_name
            if not os.path.exists(dir1):
                os.mkdir(dir1)
            productdir_list = ftp.nlst(dir_name)
            for prodir in productdir_list:
                pro_name = prodir.split('/')[-1]
                if pro_name != 'FFT_M' and pro_name != 'RAW_M':
                    print("product dir: ")      # 产品文件名目录列表
                    dir_path = dst_file_path + prodir
                    if not os.path.exists(dir_path):
                        os.mkdir(dir_path)
                    ftp_files = ftp.nlst(prodir)
                    for ftp_file in ftp_files:
                        print("ftp_file: " + ftp_file)        # 文件列表
                        write_file = dst_file_path + ftp_file
                        print("write_file: " + write_file)
                        with open(write_file, "wb") as f:
                            ftp.retrbinary('RETR %s' % ftp_file, f.write, buffer_size)
                        f.close()
        ftp.quit()

if __name__ == '__main__':
    host = "IP"
    username = "kitty"
    password = "123456"
    port = 21
    ftp_file_path = r"/data/"  # FTP目录
    dst_file_path = r"D:/测试"  # 本地目录
    ftp = FTP_OP(host=host, username=username, password=password, port=port)
    ftp.download_file(ftp_file_path=ftp_file_path, dst_file_path=dst_file_path)

PS: 我的文件有三级目录,可以根据自己的需求灵活更改。

参考目录

  • https://www.jb51.net/article/201470.htm

END

你可能感兴趣的:(Python,服务器,python)