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()
猜你喜欢
- 本文实例讲述了Python使用numpy产生正态分布随机数的向量或矩阵操作。分享给大家供大家参考,具体如下:简单来说,正态分布(Normal
- 使用 IE8 时发现其原生的 JSON 解析器存在 Bug,让我们先用 IE8 打开 DEMO 页面体验下。http://lab.grace
- 一、分析网页1. 打开网页,在搜索框输入百度翻译并进入百度翻译网站中。F12调出开发者工具,点击Network(网络)\ Fetch/XHR
- python批量命名照片的具体代码,供大家参考,具体内容如下废话不多说,上效果图全部代码from tkinter import *impor
- 1、csv简介CSV (Comma Separated Values) ,即逗号分隔值(也称字符分隔值,因为分隔符可以不是逗号),是一种常用
- 1. 日志输出到屏幕#!/usr/bin/env python# -*- coding: utf-8 -*-from __future__
- ASP里两种常用的生成文件的方式是:利用ADODB.Stream生成文件和利用Scripting.FileSystemObject(fso)
- 说明: a、以下字符中数据库名forum,数据库服务器名WWW-2443D34E558\SQL2005(或者127.0.0.1) b、查看s
- from flask import requestFlask 是一个人气非常高的Python Web框架,笔者也拿它写过一些大大小小的项目,
- 简介本文分享的实例代码主要通过python语言实现批量替换页眉页脚的操作功能,具体如下。代码#!/usr/bin/env python# -
- 自动等待及元素执行方法操作元素的一系列方法,只要调用了测试夹函数page,就能引出操作元素的方法:import pytestfrom pla
- 一、停止线程利用Threading库我们可以很方便地创建线程,让它按照我们的想法执行我们想让它执行的事情,从而加快程序运行的效率。然而有一点
- 在生产环境上,一般会使用比较健壮的Web服务器,如Apache来运行我们的应用。如果我们的Web应用是采用Python开发,而且符合WSGI
- Python绘制双轴组合的关键在plt库的twinx()函数,具体流程:1.先建立坐标系,然后绘制主坐标轴上的图表;2.再调用plt.twi
- 经常在网上冲浪的朋友是否曾注意到有些网站的鼠标不是规则的斜向上箭头的形状,而是"十"
- 本文实例讲述了python切片的步进、添加、连接简单操作。分享给大家供大家参考,具体如下:步进切片:#coding:utf-8a="
- pygame.mixer是一个用来处理声音的模块,其含义为“混音器”。游戏中对声音的处理一般包括制造声音和播放声音两部分,这里仅学习了播放声
- 本文实例讲述了python实现京东订单推送到测试环境,提供便利操作。分享给大家供大家参考,具体如下:# -*- coding: utf-8
- 首先是准备工作Python 2.7.11:下载pythonPycharm:下载Pycharm其中python2和python3目前同步发行,
- 感谢 Dawn CSS Reset 的尝试和建议。针对字体的写法,觉得需要说明一下:body,button, input, select,