FTP、SFTP文件下载内容校验

 

描述:

从FTP、SFTP下载的文件做MD5码校验,文件名和MD5码值存放在表格里,表格位置在FTP、SFTP服务器上。

os模块只能遍历本地目录/文件,需要先连接FTP、SFTP服务器,将表格下载到本地localpath,再将localpath传入exl_file_md5()函数,读取表格内容

 

1、python连接FTP、SFTP遍历目录;

2、下载目录下的Excel文件,并读取Excel文件内容,获取到Excel里的文件名和MD5码值;

3、将表格中读取出的内容以字典形式{filename:MD5}返回。

import paramiko
import xlrd
from ftplib import FTP

def sftp_down_exlfile(user,password,host,port,remotepath,localpath): t
=paramiko.Transport((host,int(port))) t.connect(username=user,password=password) sftp=paramiko.SFTPClient.from_transport(t) local_path="" for file in sftp.listdir(remotepath): if file[-5:]==".xlsx": sftp.get(os.path.join(remotepath+file),os.path.join(localpath+file)) local_path = os.path.join(localpath+file) t.close() data=exl_file_md5(local_path) return data def ftp_down_exlfile(user,password,host,port,remotepath,localpath): ftp=FTP() ftp.connect(host=host,port=int(port)) ftp.login(user=user,passwd=password) bufsize=1024 files=ftp.nlst(remotepath) ftp.cwd(remotepath)  # 切换目录,注:切换到下载的文件的远程目录 for file in files: if file[-5:]==".xlsx": fp=open(localpath,'wb') ftp.retrbinary('RETR '+file, fp.write, bufsize) fp.close() ftp.close() data=exl_file_md5(localpath) return data def exl_file_md5(exlpath): """ read Excel filename and MD5code """ try: excel=xlrd.open_workbook(exlpath) sheet=excel.sheets()[1] nrows=sheet.nrows file_md5 = {} for i in range(nrows): file_md5[sheet.row_values(i)[1]] = sheet.row_values(i)[2]return file_md5 except Exception: pass

 

posted @ 2018-04-04 11:35  申不二  阅读(3206)  评论(0编辑  收藏  举报