一、需求:
1、下载服务器更新的文件明细
2、向服务器上传明细
二、代码(没写说明,下次更新)
# coding: utf-8
import json
import yaml
import os
import random
import re
import time
import shutil
from datetime import datetime,timedelta
from dateutil.relativedelta import relativedelta
from ftplib import FTP
class FtpTools:
def __init__(self,host, username, password,remotepath, localpath):
self.ftp = FTP()
self.ftp.set_debuglevel(0)
self.ftp.connect(host, 21)
self.ftp.login(username, password)
self.remote_path = remotepath
self.local_path = localpath
def get_remote_file(self): #查找FTP目录文件列表
file_list = []
try:
self.ftp.cwd(self.remote_path)
file_list = self.ftp.nlst()
except Exception as e:
print(e)
return file_list
def get_local_file(self): #查找本地目录文件列表
file_list=[]
try:
for root, dirs, files in os.walk(self.local_path):
if len(files)>=1:
file_list = files
except Exception as e:
print (e)
return file_list
def marge_file(self,remote_files,local_files): #取差集 difference 交集 intersection 并集 union
file_list = list(set(remote_files).difference(set(local_files)))
return file_list
#从本地上传文件到ftp
def upload_file(self,file_name):
remote_file = self.remote_path + file_name
local_file = self.local_path + file_name
print(file_name)
bufsize = 1024
try:
file_handle = open(local_file, 'rb')
self.ftp.storbinary('STOR ' + remote_file, file_handle, bufsize)
self.ftp.set_debuglevel(0)
except Exception as e:
print(e)
#从ftp下载文件
def down_file(self,file_name):
remote_file = self.remote_path + file_name
local_file = self.local_path + file_name
bufsize = 1024
file_handle = open(local_file, 'wb').write
self.ftp.retrbinary('RETR ' + remote_file, file_handle, bufsize)
self.ftp.set_debuglevel(0)
def run_down_load(self):
#1.0 获取FTP目录文件列表
list_remote_files = self.get_remote_file()
#2.0 获取本地目录列表
list_local_files = self.get_local_file()
#3.0 取差集
list_down_files = self.marge_file(list_remote_files,list_local_files)
#4.0 下载差集对应的文件
for file_name in list_down_files:
if len(file_name) >= 5 :
self.down_file(file_name)
#关闭ftp连接
self.ftp.quit()
def run_upload(self):
#1.0 获取FTP目录文件列表
list_remote_files = self.get_remote_file()
#3.0 上传文件
for file in self.get_local_file():
file_full_path = self.local_path + file
print('file_full_path: ' ,file_full_path)
if os.path.exists(file_full_path):
self.upload_file(file)
print('ok')
#关闭ftp连接
self.ftp.quit()
if __name__ == "__main__":
'''
#下载
host = '190.168.1.101'
username = 'ftp'
password = 'ftp'
remotepath = '/mms_data/' #远程FTP路径
localpath = 'D:/ftp_file/datas/' #本地路径
ftp_file = FtpTools(host, username, password,remotepath, localpath)
ftp_file.down_file()
'''
#上传
host = '190.168.1.101'
username = 'ftp'
password = 'ftp'
remotepath = '/mms_data/' #远程FTP路径
localpath = 'D:/ftp_file/datas/' #本地路径
ftp_file = FtpTools(host, username, password,remotepath, localpath)
ftp_file.run_upload()