python实现从ftp服务器下载文件
作者:stalk58 发布时间:2022-04-30 18:54:53
标签:python,ftp,下载文件
代码之余,将代码过程重要的一些代码段备份一下,如下的代码内容是关于Python从ftp服务器下载文件的的代码,希望能对小伙伴有用途。
#coding=utf-8
'''
ftp自动下载、自动上传脚本,可以递归目录操作
'''
from ftplib import FTP
import os,sys,string,datetime,time
import socket
class MYFTP:
def __init__(self, hostaddr, username, password, remotedir, port=21):
self.hostaddr = hostaddr
self.username = username
self.password = password
self.remotedir = remotedir
self.port = port
self.ftp = FTP()
self.file_list = []
# self.ftp.set_debuglevel(2)
def __del__(self):
self.ftp.close()
# self.ftp.set_debuglevel(0)
def login(self):
ftp = self.ftp
try:
timeout = 300
socket.setdefaulttimeout(timeout)
ftp.set_pasv(True)
print u'开始连接到 %s' %(self.hostaddr)
ftp.connect(self.hostaddr, self.port)
print u'成功连接到 %s' %(self.hostaddr)
print u'开始登录到 %s' %(self.hostaddr)
ftp.login(self.username, self.password)
print u'成功登录到 %s' %(self.hostaddr)
debug_print(ftp.getwelcome())
except Exception:
print u'连接或登录失败'
try:
ftp.cwd(self.remotedir)
except(Exception):
print u'切换目录失败'
def is_same_size(self, localfile, remotefile):
try:
remotefile_size = self.ftp.size(remotefile)
except:
remotefile_size = -1
try:
localfile_size = os.path.getsize(localfile)
except:
localfile_size = -1
debug_print('localfile_size:%d remotefile_size:%d' %(localfile_size, remotefile_size),)
if remotefile_size == localfile_size:
return 1
else:
return 0
def download_file(self, localfile, remotefile):
if self.is_same_size(localfile, remotefile):
debug_print(u'%s 文件大小相同,无需下载' %localfile)
return
else:
debug_print(u'>>>>>>>>>>>>下载文件 %s ... ...' %localfile)
#return
file_handler = open(localfile, 'wb')
self.ftp.retrbinary(u'RETR %s'%(remotefile), file_handler.write)
file_handler.close()
def download_files(self, localdir='./', remotedir='./'):
try:
self.ftp.cwd(remotedir)
except:
debug_print(u'目录%s不存在,继续...' %remotedir)
return
if not os.path.isdir(localdir):
os.makedirs(localdir)
debug_print(u'切换至目录 %s' %self.ftp.pwd())
self.file_list = []
self.ftp.dir(self.get_file_list)
remotenames = self.file_list
#print(remotenames)
#return
for item in remotenames:
filetype = item[0]
filename = item[1]
local = os.path.join(localdir, filename)
if filetype == 'd':
self.download_files(local, filename)
elif filetype == '-':
self.download_file(local, filename)
self.ftp.cwd('..')
debug_print(u'返回上层目录 %s' %self.ftp.pwd())
def upload_file(self, localfile, remotefile):
if not os.path.isfile(localfile):
return
if self.is_same_size(localfile, remotefile):
debug_print(u'跳过[相等]: %s' %localfile)
return
file_handler = open(localfile, 'rb')
self.ftp.storbinary('STOR %s' %remotefile, file_handler)
file_handler.close()
debug_print(u'已传送: %s' %localfile)
def upload_files(self, localdir='./', remotedir = './'):
if not os.path.isdir(localdir):
return
localnames = os.listdir(localdir)
self.ftp.cwd(remotedir)
for item in localnames:
src = os.path.join(localdir, item)
if os.path.isdir(src):
try:
self.ftp.mkd(item)
except:
debug_print(u'目录已存在 %s' %item)
self.upload_files(src, item)
else:
self.upload_file(src, item)
self.ftp.cwd('..')
def get_file_list(self, line):
ret_arr = []
file_arr = self.get_filename(line)
if file_arr[1] not in ['.', '..']:
self.file_list.append(file_arr)
def get_filename(self, line):
pos = line.rfind(':')
while(line[pos] != ' '):
pos += 1
while(line[pos] == ' '):
pos += 1
file_arr = [line[0], line[pos:]]
return file_arr
def debug_print(s):
print s
if __name__ == '__main__':
timenow = time.localtime()
datenow = time.strftime('%Y-%m-%d', timenow)
# 配置如下变量
hostaddr = '211.15.113.45' # ftp地址
username = 'UserName' # 用户名
password = '123456' # 密码
port = 21 # 端口号
rootdir_local = 'E:/mypiv' # 本地目录
rootdir_remote = '/PIV' # 远程目录
f = MYFTP(hostaddr, username, password, rootdir_remote, port)
f.login()
f.download_files(rootdir_local, rootdir_remote)
timenow = time.localtime()
datenow = time.strftime('%Y-%m-%d', timenow)
logstr = u"%s 成功执行了备份n" %datenow
debug_print(logstr)
来源:https://blog.csdn.net/stalk58/article/details/100071233


猜你喜欢
- 前言python与C/C++不一样,它的变量使用有自己的特点,当初学python的时候,一定要记住“一切皆为对象,一切皆为对象的引用”这句话
- 但是有时候,可以视看处进逻辑程度,可以把三者写成一个触发器,只是在其中稍作判断而已。 你可以根据从下面方法判断触发器是是处理了插入,删除还是
- 前言 Tensorflow中可以使用tensorboard这个强大的工具对计算图、loss、网络参数等进行可视化。本文并不涉及对tensor
- 我们在微博上可以对图片进行向左转向右转等旋转操作,让用户可以从不同的视角欣赏图片效果。本文将结合实例为您讲解如何使用Javascript结合
- Python 在命令行解析方面给出了类似的几个选择:自己解析, 自给自足(batteries-included)的方式,以及大量的
- 我就废话不多说了,大家还是直接看代码吧~func GetGID() uint64 { b := make([]by
- 本文所用环境:Python 3.6.5 |Anaconda custom (64-bit)|引言由于某些原因,需要用python读取二进制文
- sql server中如何判断表或者数据库的存在,但在实际使用中,需判断Status状态位:其中某些状态位可由用户使用 sp_dboptio
- 需求是:针对三篇英文文章进行分析,计算出现次数最多的 10 个单词逻辑很清晰简单,不算难, 使用 python 读取多个 txt 文件,将文
- 有关itchat接口的知识,小编是初步学习,这里先给大家分享一段代码用法示例。sudo pip3 install itchat今天用了下it
- 作者:xiaolanLin声明 :本文版权归作者和博客园共有,来源网址:https://www.cnblogs.com/xiaolan-Li
- 天我们看看import的有关内容。编程时总是用到import导入,动不动就导入,很简单,但import到底是个什么功能,它的本质是什么?一.
- <% Response.Buffer = True Server.ScriptTimeOut=9999999&
- Vue实践分享(三)在实际项目的开发过程中,经常会遇到页面还没渲染完成而插件就已经开始加载的问题,这样就会导致显示和功能出错。可以通过Vue
- 目录优化排序查询避免重复获取刚刚修改的数据行懒加载的联合查询优化排序查询自定义变量的一个重要特性是你可以同时将该变量的数学计算后的结果再赋值
- 整理文档,搜刮出Node.js查找当前目录下文件夹实例代码,稍微整理精简一下做下分享。var http = require("ht
- 学习目标在本章中,将学习用于跟踪视频中对象的Meanshift和Camshift算法MeanshiftMeanshift背后的原理很简单,假
- echarts legend点击事件首先,明确本篇文章的重点,主要有三个:1. 给legend添加点击事件2. 禁用legend点击事件的默
- 单向链表单向链表也叫单链表,是链表中最简单的一种形式,它的每个节点包含两个域,一个信息域(元素域)和一个链接域。这个链接指向链表中的下一个节
- 第七步: 在自定义分页的Repeater 里添加排序功能现在已经完成了自定义分页,我们再来添加排序功能。ProductsBLL类的GetPr