用class定义ftp工具的各种方法

import os,sys
from ftplib import FTP
from mimetypes import guess_type,add_type
from getpass import getpass #定义默认配置
dfltSite = '192.168.191.1'
dfltUser = ()
dfltRdir = '.' class FtpTools: #allows these 3 to be redefined
def getlocaldir(self):
return (len(sys.argv) > 1 and sys.argv[1]) or '.' #返回本地路径 def getcleanall(self):
return input( 'Clean local directory first? ')[:1] in ['y','Y'] #是否清除所有
#暂且不用
# def getpassword(self):
# print('password')
# return getpass('Password for %s on %s'%(self.remoteuser,self.remotesite)) #键入密码
#配置
def configTransfer(self,site=dfltSite,rdir=dfltRdir,user=dfltUser):
self.nonpassive = False # passive FTP by default
self.remotesite = site
self.remotedir = rdir # FTP的路径
self.remoteuser = user # 因为我没设置密码,所以为空集 self.localdir =self.getlocaldir()
self.cleanall = self.getcleanall()
self.remotepass = '' #密码

#判断文件格式
def isTextKind(self,remotename,trance=True):
''' use mimetypes to guess if filanme means text or binary''' add_type('text/x-python-win','.pyw') #not in tables
mimetype, encoding = guess_type(remotename,strict=False) #allow extras
mimetype = mimetype or '?/?'
mimetype = mimetype.split('/')[0]
if trance: print(mimetype,encoding or '')
return mimetype == 'text' and encoding == None #连接服务器
def connectFtp(self): # 连接PFTP
print('connecting...')
connection = FTP(self.remotesite)
connection.login(self.remoteuser,self.remotepass)
connection.cwd(self.remotedir) #most do passive
if self.nonpassive:
connection.set_pasv(False)
self.connection = connection

#清除本地文件
def cleanLocals(self):
'''try to delete all local files first to remove garbage''' #清除本地文件 if self.cleanall:
for localname in os.listdir(self.localdir):
try:
print('deleting local', localname)
os.remove(os.path.join(self.remotedir, localname))
except:
print('cannot delete', localname)

#清除远程文件
def cleanRemotes(self):
'''try to delete all remote files to remove garbage''' if self.cleanall:
for remotename in self.connection.nlst():
try:
print('deleting local', remotename)
self.connection.delete(remotename)
except:
print('cannot delete', remotename) #下载文件
def downloadOne(self,remotename,localpath):
if self.isTextKind(remotename):
localfile = open(localpath,'w',encoding=self.connection.encoding)
def callback(line): localfile.write(line + '\n')
self.connection.retrlines('RETR '+remotename,callback)
else:
localfile = open(localpath,'wb')
self.connection.retrbinary('RETR ' + remotename, localfile.write)
localfile.close() #上传文件
def uploadOne(self, localname,remotename, localpath):
if self.isTextKind(localname):
localfile = open(localpath,'rb')
self.connection.storlines('RETR ' + remotename, localfile) else:
localfile = open(localpath, 'rb')
self.connection.storbinary('RETR '+remotename,localfile)
localfile.close() #下载目录
def downloadDir(self):
remotefiles = self.connection.nlst()
for remotename in remotefiles:
if remotename in ('.', '..') or not '.' in remotename: continue # 判断是否目录,这里根据实际情况更改
localpath = os.path.join(self.localdir, remotename)
print('downing', remotename, 'to', localpath, 'as',end=' ')
self.downloadOne(remotename,localpath)
print('Done',len(remotefiles),'files downloaded') #上传目录
def uploadDir(self):
localfiles = os.listdir(self.localdir)
for localname in localfiles:
localpath = os.path.join(self.localdir, localname)
print('uploading', localpath, 'to', localname, 'as',end=' ')
self.uploadOne(localname,localpath,localname)
print('Done',len(localfiles),'files uploaded') def run(self,cleanTarget=lambda:None, transferAct=lambda:None): self.connectFtp()
cleanTarget()
transferAct()
self.connection.quit() if __name__ == '__main__':
ftp = FtpTools()
xfermode = 'download'
if len(sys.argv) > 1:
xfermode = sys.argv.pop(1)
if xfermode == 'download':
ftp.configTransfer()
ftp.run(cleanTarget=ftp.cleanLocals, transferAct=ftp.downloadDir)
if xfermode == 'upload':
ftp.configTransfer(site='192.168.191.1') #根据自己情况更改IP
ftp.run(cleanTarget=ftp.cleanRemotes, transferAct=ftp.uploadDir)
else:
print('Usage: ftptools.py["download/upload"] [loacldir] ')

2.5 定义FTP工具的各种方法的更多相关文章

  1. Linux环境下FTP工具的使用方法

    在Windows环境下创建Ftp目录作为服务器根目录 在Linux端的操作: 从服务器端下载文件到Linux端: ftpget -u User -p Password ServerIP File Fi ...

  2. java:工具(汉语转拼音,压缩包,EXCEL,JFrame窗口和文件选择器,SFTP上传下载,FTP工具类,SSH)

    1.汉语转拼音: import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuP ...

  3. 深入理解为什么Java中方法内定义的内部类可以访问方法中的局部变量

    好文转载:http://blog.csdn.net/zhangjg_blog/article/details/19996629 开篇 在我的上一篇博客 深入理解Java中为什么内部类可以访问外部类的成 ...

  4. 详述Linux ftp命令的使用方法

    转自:http://os.51cto.com/art/201003/186325.htm ftp服务器在网上较为常见,Linux ftp命令的功能是用命令的方式来控制在本地机和远程机之间传送文件,这里 ...

  5. windows快速搭建FTP工具Serv-U FTP Server

    本文介绍一个简单的FTP工具,当然windows系统自带FTP工具,但是配置方法没有第三方工具来的简单可操作性好. 此工具用于搭建FTP环境,对于需要测试FTP上传功能具有极大帮助.例如球机抓拍图片上 ...

  6. 翻译:Laravel-4-Generators 使用自己定义代码生成工具高速进行Laravel开发

    使用自己定义代码生成工具高速进行Laravel开发 这个Laravle包提供了一种代码生成器,使得你能够加速你的开发进程.这些生成器包含: generate:model – 模型生成器 generat ...

  7. 详述Centos中的ftp命令的使用方法

    ftp服务器在网上较为常见,Linux ftp命令的功能是用命令的方式来控制在本地机和远程机之间传送文件,这里详细介绍Linux ftp命令的一些经常使用的命令,相信掌握了这些使用Linux 进行ft ...

  8. [Windows Server 2003] IIS自带FTP安装及配置方法

    ★ 欢迎来到[护卫神·V课堂],网站地址:http://v.huweishen.com★ 护卫神·V课堂 是护卫神旗下专业提供服务器教学视频的网站,每周更新视频.★ 本节我们将带领大家:IIS6.0自 ...

  9. OpenJDK源码研究笔记(四)-编写和组织可复用的工具类和方法

    本篇主要讲解java.util.Arrays这个针对数组的工具类. 1.可复用的工具类和方法.  这个工具类里,包含很多针对数组的工具方法,如 排序.交换.二分查找.比较.填充.复制.hashcode ...

随机推荐

  1. Hadoop -- 概念

    hadoop 一个开源的,稳定的,可扩展的,分布式的计算框架 实现单一的服务器到成千上万机器之间共同处理数据的一个可扩展性框架 Hadoop 项目主要包含以下四个模块 Hadoop Common:为其 ...

  2. jmeter获取mysql数据并作为请求参数使用

    1.将mysql-connector-java-5.1.22-bin.jar包放到jmeter的lib目录下,重启jmeter 2.测试计划中添加jdbc connection,右键测试计划----添 ...

  3. undefined的几种情况

    1.变量声明了,但是没有赋值: 2.一个变量声明了,并且赋值了undefined: var a = undefined; 3.一个对象中,获取某个不存在的属性,值也是undefined

  4. 服务器日志文件Web远程查看

    公司买的一款企业应用软件,所有透过应用操作DB的操作都会生成有日志,日志是以文本文件的形式存放在服务器上,后缀名为*.log.1,*.log.2之类的,软件本身也提供功能查询这些日志,但这个查询的功能 ...

  5. C++的重载操作符(operator)介绍(转)

    本文主要介绍C++中的重载操作符(operator)的相关知识. 1. 概述 1.1 what operator 是C++的一个关键字,它和运算符(如=)一起使用,表示一个运算符重载函数,在理解时可将 ...

  6. MySQL中SQL语句2

    上一片介绍了一些基本的SQL的增删改查,这一片会介绍一些进阶的SQL语句使用. MySQL中的视图 视图是什么?当我们总是查询几张表的某个字段时,可以创建一张虚拟表,把这几个字段写入这个虚拟的表,这样 ...

  7. Python关键点笔记之使用 pyenv 管理多个 Python 版本依赖环境

    0x00 背景 从接触Python以来,一直都是采用virtualenv和virtualenvwrapper来管理不同项目的依赖环境,通过workon.mkvirtualenv等命令进行虚拟环境切换, ...

  8. 02: OpenStack

    1.1 OpenStack各组件 1.Horizon(控制台),又名Dashboard 就是web展示界面操作平台,方便用户交互的 2.Nova(计算) 负责创建,调度,销毁云主机 3.Neutron ...

  9. Windows下Python安装numpy+mkl,Scipy和statsmodels

    最近做时间序列分析需要用到Python中的statsmodels,但是安装过程中遇到很头疼的问题,Google.Stackover各种都没有找到合适的解决办法,而且貌似还有很多同学也在吐槽Window ...

  10. Kotlin 基本数据类型

    Kotlin 的基本数值类型包括 Byte.Short.Int.Long.Float.Double 等.不同于Java的是,字符不属于数值类型,是一个独立的数据类型. 类型 位宽度 Double 64 ...