1.只用ftp实现上传下载功能
from ftplib import FTP
import os
class MyFTP:
def __init__(self):
'''ftp服务器主机IP,端口等配置'''
self.ftp_host = "***.**.**.***"
self.ftp_port = 21
self.ftp_user = '***'
self.ftp_passwd = '***'
self.ftp = FTP()
def get_ftp_host(self):
return self.ftp_host
def get_ftp_port(self):
return self.ftp_port
def get_ftp_user(self):
return self.ftp_user
def get_ftp_passwd(self):
return self.ftp_passwd
# 连接到ftp服务器
def connect(self):
print('is connecting to ftp server %s on %s' % (self.ftp_host, self.ftp_port))
self.ftp.connect(self.ftp_host, self.ftp_port)
# 登陆到ftp服务器
def login(self):
print('ready to login ftp server')
self.ftp.login(self.ftp_user, self.ftp_passwd)
print('login ftp server successfully')
print(self.ftp.getwelcome())
# 友好的关闭连接
def quit(self):
try:
self.ftp.quit()
print('colose ftp connection successfully')
except Exception as e:
print('%s' % e)
# 上传文件夹
def upload_folder(self, local_path, remote_path):
if not os.path.isdir(local_path):
print('出错了,请选择要上传的文件夹')
return
local_path = local_path.strip() # 以防万一,去除首尾空格
local_path = local_path.rstrip('/') # 去除右部 /
local_path = local_path.rstrip('\\') # 去除右部 \\
remote_path = remote_path.strip()
remote_path = remote_path.rstrip('/')
remote_path = remote_path.rstrip('\\')
self.ftp.cwd(remote_path)
last_dir = os.path.basename(local_path)
print(last_dir)
remote_path = os.path.join(remote_path, last_dir)
print(remote_path)
remote_path = remote_path.replace('\\', '/') # 转为linux标准路径
print(remote_path)
# # 如果ftp服务器上不存在该路径,则创建对应路径下的目录
# try:
# self.ftp.mkd(last_dir)
# except:
# # print('dir: %s already exists' % last_dir)
# pass
#
# sub_items = os.listdir(local_path)[:2]
# print(sub_items)
# for sub_item in sub_items:
# sub_item_path = os.path.join(local_path, sub_item)
# if os.path.isdir(sub_item_path): # 如果子项目为目录
# self.upload_folder(sub_item_path, remote_path)
# else:
# self.upload_file(sub_item_path, remote_path)
# 上传文件
def upload_file(self, src_file_path, remote_path):
remote_file_name = os.path.split(src_file_path)[1]
remote_path = remote_path + '/' + remote_file_name
# try: # 如果文件不存在,调用file.size(filename)会报错
# if self.ftp.size(remote_path)