Files
test/sf_mrs_connect/models/ftp_operate.py
2023-11-21 16:10:05 +08:00

46 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
import os
from ftplib import FTP
import logging
# FTP接口类
class FtpController():
'''
这是ftp接口类在类初始化的时候就连接了ftp服务器能否成功连接有反馈。
类中定义了两个接口:上传接口和删除接口
'''
ftp = FTP()
def __init__(self, host, port, username, password):
try:
self.ftp.connect(host, port)
self.ftp.login(username, password)
logging.info("ftp连接成功")
except Exception:
logging.info("ftp连接失败")
# 下载目录下的文件
def download_file_tree(self, target_dir, serverdir):
if not os.path.exists(serverdir):
os.makedirs(serverdir)
try:
logging.info("进入FTP目录 ")
self.ftp.cwd(target_dir) # 切换工作路径
logging.info('FTP目录:%s' % target_dir)
remotenames = self.ftp.nlst()
logging.info('FTP目录文件:%s' % remotenames)
for file in remotenames:
server = os.path.join(serverdir, file)
if file.find(".") != -1:
self.download_file(server, file)
except Exception:
return False
# 下载指定目录下的指定文件
def download_file(self, serverfile, remotefile):
file_handler = open(serverfile, 'wb')
self.ftp.retrbinary('RETR ' + remotefile, file_handler.write)
file_handler.close()