文章目录
1. ftp工具类
编写ftp工具类,我这里取名为 ftp_util.py
import os
from ftplib import FTP
class FtpUtil:
def __init__(self, ip, username, password, port=21):
self.ip = ip
self.username = username
self.password = password
self.port = port
self.ftp = None
def connect(self):
''''建立ftp远程连接'''
try:
self.ftp = FTP()
self.ftp.connect(host=self.ip, port=self.port)
self.ftp.login(user=self.username, passwd=self.password)
except Exception as e:
print(e)
def disconnect(self):
''''断开远程连接'''
if self.ftp:
self.ftp.quit()
def upload_file(self, localPath, remotePath, mode='binary'):
'''上传文件'''
try:
with open(localPath, 'rb') as f:
if mode == 'binary': # 上传二进制文件
self.ftp.storbinary(f'STOR {
remotePath}', f)
elif mode == 'text': # 上传文本文件
self.ftp.storlines(f'STOR {
remotePath}', f)
print(f'文件已上传,本地文件路径:{
localPath},远端文件路径:{
remotePath}')
except Exception as e:
print(f'文件上传失败:{
e}')
def download_file(self, localPath, remotePath, mode='binary'):
'''下载文件'''
try:
with open(localPath, 'wb') as f:
if mode == 'binary': # 下载二进制文件
self.ftp.retrbinary(f'RETR {
remotePath}&#