python2 利用ftp下载文件

weqeqwftp.png

登陆 ftp 服务器下载文件

    import os

    def get_ftp_server_file(cls, dir_ftp, filename, host, port, username, password):
        """
        登陆 ftp 服务器下载文件(保存到项目根目录)
        :param dir_ftp: 目标文件在 ftp 服务器上路径;
        :param filename: 目标文件名;
        :param host: ftp 服务器地址(ip/域名);
        :param port: ftp 服务器端口号,一般是 21;
        :param username: 登陆 ftp 服务器时的用户名
        :param password: 登陆 ftp 服务器时的密码
        :return boolean
        """
        if os.path.exists(filename):
            logging.info(u'FTP:文件 ' + filename + u' 已经存在!该文件将被重复写入')
        # 开始连接
        try:
            f = ftplib.FTP()
            f.connect(host=host, port=port)
        except (socket.error, socket.gaierror), e:
            msg = u"FTP: 不能连接到ftp服务器({}),请检查ftp服务器是否正常工作!".format(host)
            logging.info(msg)
            raise UserError(msg)
        # 登录
        try:
            f.login(user=username, passwd=password)
        except ftplib.error_perm, e:
            msg = u"Ftp: 不能登录到FTP服务器,请检查账户名和密码及端口是否正确!"
            f.quit()
            raise UserError(msg)
        msg = u"用户{}已登录ftp服务器{}".format(username, host)
        logging.info(msg)
        try:
            f.cwd(dir_ftp)
        except ftplib.error_perm, e:
            msg = u"FTP:路径{}在ftp服务器{}中无法打开!".format(dir_ftp, host)
            logging.info(msg)
            f.quit()
            raise UserError(msg)
        # 获取文件
        f.set_pasv(0)
        try:
            logging.info(u'>>>>>>>>>>>>下载文件 {} ... ...'.format(filename))
            buf_size = 999999
            f.retrbinary('RETR {}'.format(filename), open(filename, 'wb').write, buf_size)
        except Exception as e:
            msg = u"FTP:读取文件失败, 文件{}在{}中!".format(filename, host)
            logging.info(e)
            os.unlink(filename)
            logging.info(msg)
            raise UserError(msg)
        else:
            os.getcwd()
            # 获取完成后删除ftp中的远程文件
            # f.delete(filename)
            f.quit()
            logging.info(u">>>>>>>>>>>>成功下载文件:{},保存在项目根目录!".format(filename))
            return True
Last modification:January 10th, 2019 at 05:58 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment