Python FTP使用(下载文件和文件夹)

参考代码


# -*- encoding=utf-8 -*-
import ftplib
import os

from common.LogConfig import log

ROOT = 'ROOT'


class FTPOperate:
def __init__(self, ip, port, user, password):
self.ip = ip
self.port = int(port)
self.user = user
self.password = password
self.ftp = ftplib.FTP() # new一个ftp对象

def connect(self):
try:
self.ftp.connect(self.ip, self.port) # 连接ftp
log.info('Connection ftp success')
except Exception as e:
log.error('Connection ftp fail:{}'.format(e))

def login(self):
try:
self.ftp.login(self.user, self.password) # 登录ftp
log.info('Login ftp success')
except Exception as e:
log.error('Login ftp fail:{}'.format(e))

def cwd_root(self):
try:
self.ftp.cwd('/') # 切换到根目录
log.info('Cd ftp root success')
except Exception as e:
log.error('Cd ftp root fail:{}'.format(e))

def cwd(self, path, relative=''):
"""
Switch relative to the root directory if relative is ROOT,
or switch relative to the current directory
:param path:
:param relative:
:return:
"""
if relative.upper() == ROOT:
self.cwd_root()
try:
self.ftp.cwd(path) # 切换到任意目录
log.info('Cd ftp dir success:{}'.format(path))
except Exception as e:
log.error('Cd ftp dir fail:{}'.format(e))

def pwd(self):
current_dir = ''
try:
current_dir = self.ftp.pwd() # 获取当前的目录
log.info('Get ftp current dir success:{}'.format(current_dir))
except Exception as e:
log.error('Get ftp current dir fail:{}'.format(e))
return current_dir

def close(self):
try:
self.ftp.close() # 关闭
log.info('Close ftp success')
except Exception as e:
log.error('Close ftp fail:{}'.format(e))

@staticmethod
def create_folder(folder):
folder = os.path.abspath(folder)
if not os.path.exists(folder):
try:
os.makedirs(folder)
log.info('Create folder success:{}'.format(folder))
except Exception as e:
log.error('Create folder fail:{}'.format(e))

def down_file(self, ftp_file, save_local_path):
success = False
abs_path = os.path.abspath(save_local_path)
path = os.path.dirname(save_local_path)
self.create_folder(path)
try:
with open(abs_path, 'wb') as f:
ret = self.ftp.retrbinary('RETR ' + ftp_file, f.write) # 下载文件
log.info('Down ftp file return:{}'.format(ret))
if ret.startswith('226'):
log.info('Down ftp file success, save to:{}'.format(abs_path))
success = True
except Exception as e:
log.error('Down ftp file fail:{}'.format(e))
log.error('Fail path:{}'.format(ftp_file))
success = False
return success

def get_dir_and_files(self, ftp_path):
# 获取路径的文件夹和文件
path_info = []
folder = []
files = []
try:
self.ftp.dir(ftp_path, path_info.append)
except Exception as e:
log.error('Get ftp dir fail:{}'.format(e))
log.error('Fail path:{}'.format(ftp_path))
for path in path_info:
path = path.strip()
filename = ftp_path + '/' + path.split(':')[1][3:]
if path.startswith('-'):
files.append(filename)
elif path.startswith('d'):
folder.append(filename)
else:
log.error('Can not tell whether it is a folder or a file:{}'.format(path))
return folder, files

def down_folder(self, ftp_path, local_path):
# 下载文件夹
local_path = os.path.abspath(local_path)
dirs, all_file = self.get_dir_and_files(ftp_path)
for one_dir in dirs:
self.down_folder(one_dir, local_path)
for one_file in all_file:
save_path = local_path + one_file
self.down_file(one_file, save_path)


def debug():
ip = '10.190.50.55'
port = '21'
user = 'admin'
password = 'admin'
ftp = FTPOperate(ip, port, user, password)
ftp.connect()
ftp.login()
ftp.pwd()
ftp.down_file('/a/log.log', './A/a/log.log')
ftp.down_folder('/BBB', './BBB')
ftp.close()


if __name__ == '__main__':
pass
debug()
 

 

posted @ 2020-11-18 10:44  南风丶轻语  阅读(2115)  评论(0编辑  收藏  举报