Python FTP操作类代码分享
发布时间:2022-09-07 17:59:23
#!/usr/bin/py2
# -*- coding: utf-8 -*-
#encoding=utf-8
'''''
ftp自动下载、自动上传脚本,可以递归目录操作
'''
from ftplib import FTP
import os, sys, string, datetime, time
import socket
class FtpClient:
def __init__(self, host, user, passwd, remotedir, port=21):
self.hostaddr = host
self.username = user
self.password = passwd
self.remotedir = remotedir
self.port = port
self.ftp = FTP()
self.file_list = []
def __del__(self):
self.ftp.close()
def login(self):
ftp = self.ftp
try:
timeout = 60
socket.setdefaulttimeout(timeout)
ftp.set_pasv(True)
ftp.connect(self.hostaddr, self.port)
print 'Connect Success %s' %(self.hostaddr)
ftp.login(self.username, self.password)
print 'Login Success %s' %(self.hostaddr)
debug_print(ftp.getwelcome())
except Exception:
deal_error("Connect Error or Login Error")
try:
ftp.cwd(self.remotedir)
except(Exception):
deal_error('Change Directory Error')
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('lo:%d re:%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):
return
else:
pass
file_handler = open(localfile, 'wb')
self.ftp.retrbinary('RETR %s'%(remotefile), file_handler.write)
file_handler.close()
def download_files(self, localdir='./', remotedir='./'):
try:
self.ftp.cwd(remotedir)
except:
return
if not os.path.isdir(localdir):
os.makedirs(localdir)
self.file_list = []
self.ftp.dir(self.get_file_list)
remotenames = self.file_list
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('..')
def upload_file(self, localfile, remotefile):
if not os.path.isfile(localfile):
return
if self.is_same_size(localfile, remotefile):
return
file_handler = open(localfile, 'rb')
self.ftp.storbinary('STOR %s' %remotefile, file_handler)
file_handler.close()
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('Directory Exists %s' %item)
self.upload_files(src, item)
else:
self.upload_file(src, item)
self.ftp.cwd('..')
def mkdir(self, remotedir='./'):
try:
self.ftp.mkd(remotedir)
except:
debug_print('Directory Exists %s' %remotedir)
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(str):
print (str)
def deal_error(e):
timenow = time.localtime()
datenow = time.strftime('%Y-%m-%d', timenow)
logstr = '%s Error: %s' %(datenow, e)
debug_print(logstr)
file.write(logstr)
sys.exit()


猜你喜欢
- 解决golang编译提示dial tcp 172.217.160.113:443: connectex: A connection atte
- 前言随着深度学习的不断发展,从开山之作Alexnet到VGG,网络结构不断优化,但是在VGG网络研究过程中,人们发现随着网络深度的不断提高,
- 很多时候学习是一种难者不会,会者不难的事情。下面的5个python技巧是性价比极高的知识点,一学就会,不难但是相当管用。使用交互模式使用py
- 说明:几个简单的基本的sql语句 选择:select * from table1 where 范围 插入:insert into table
- python 使用get_argument获取url query参数ornado的每个请求处理程序,我们叫做handler,handler里
- # 贪婪模式 默认的匹配规则# 在满足条件的情况下 尽可能多的去匹配到字符串import rers = re.match('\d{6
- 测试环境:1:xp系统2:双显,1680×1050 + 1050×16803:chrome 版本4.14:ff版本3.6chrome是我的默
- 本文实例讲述了Python图像处理实现两幅图像合成一幅图像的方法。分享给大家供大家参考,具体如下:将两幅图像合成一幅图像,是图像处理中常用的
- 动态生成的IFRAME,设置SRC时的,不同位置带来的影响。以下所说的是在IE7下运行的。IE6下也是同样。在这个blog中,直接点击运行代
- 公司安排了个任务,爬取ppt资源,我爬取后打开ppt发现,最后一页是站点的宣传,需要删除。仔细阅读了python-pptx的api和国内的教
- 听歌识曲,顾名思义,用设备“听”歌曲,然后它要告诉你这是首什么歌。而且十之八九它还得把这首歌给你播放出来。这样的功能在QQ音乐等应用上早就出
- 一、创建元组tup1 = ('physics', 'chemistry', 1997, 2000);tup2
- E盘根目录新建一个Excel文件aa.xls后测试如下代码use tempdb go if (object_id ('udf_get
- 一、定义协程asyncio 执行的任务,称为协程,但是Asyncio 并不能带来真正的并行Python 的多线程因为 GIL(全局解释器锁)
- 继打游戏、看视频等摸鱼行为被监控后,现在打工人离职的倾向也会被监控。有网友爆料称知乎正在低调裁员,视频相关部门几乎要裁掉一半。而在知乎裁员的
- 使用Opencv打开笔记本电脑摄像头报错近期要做一个下位机上发图像数据给上位机的任务,调试时自己写了一个客户端获取笔记本电脑的摄像头视频数据
- 我就废话不多说了,直接上代码吧!#2.14from turtle import *from time import sleepdef go_
- 类中定义的方法大致可以分为两类:绑定方法和非绑定方法。其中绑定方法又可以分为绑定到对象的方法和绑定到类的方法。一、绑定方法1 对象的绑定方法
- 咱们Python 集中营有一个专题就是分享一些有意思的东西,今天大概看了一下pygame的这个非标准库就想着使用它来做个小游戏-拼图。通过加
- collections是Python内建的一个集合模块,提供了许多有用的集合类。这里举几个例子:namedtuple我们知道tuple可以表