用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. div “下沉”

    最近在做一个计算器,按键整体布局如下: Div2,div3 display属性设置为inline-block.三个div “容器”没添加任何元素时,布局是符合预想的.添加上按键后,布局变成下面这样了: ...

  2. 记录Js 文本框验证 与 IE兼容性

    最近的日常就是将测试小姐姐提交的bug进行修改,想来这种事情还是比较好开展的,毕竟此项目已上线一年多,现在只是一些前端的问题需要改正.实际上手的时候并不是这样,原项目是在谷歌上运行,后来由于要新增一个 ...

  3. linux C access

    [1]作用 确定文件的访问权限 [2]头文件 #include <unistd.h> [3]函数定义 int access(const char * pathname,  int mode ...

  4. eleemnt-ui修改主题颜色

    饿了吗的element-ui使用的是淡蓝色的主题,有时候我们可以自定义主题,官方的文档给我们提供了如何修改主题,介绍的很详细,自己试验过后,觉得很不错,一方面怕忘记,一方面写一写. 方法一是在线生成一 ...

  5. oracle 误删除数据,回退表数据

    select * from sh_gonghuo_renyuan as of timestamp to_timestamp('2017-11-17 16:00:00','yyyy-mm-dd hh24 ...

  6. 使用solr进行配置文件

    我现在使用的是一个已经搭建好的solr环境下进行的测试: 第一步,需要配置solrhome中的一个配置文件schema.xml 配置内容如下,上面配置的是IK分词器,下面是配置完成的域. 因为我在这个 ...

  7. Solr全文检索框架

    概述: 什么是Solr? Solr是Apache下的一个顶级开源项目,采用Java开发,它是基于Lucene的全文搜索服务.Solr可以独立运行在Jetty.tomcat.webLogic.webSh ...

  8. spring boot +mybatis 整合 连接数据库测试(从0到1)

    spring boot 整合mybatis 1.打开idea创建一个项目 2.在弹出的窗口中选择spring initializr(初始化项目),点击next 3.接下来填写group 与artifa ...

  9. WEB 前端插件整理

    Vs Code 系统插件 #1 Bracket Pair Colorizer 让括号拥有独立的颜色,易于区分.可以配合任意主题使用. #2 Code Runner 非常强大的一款插件,能够运行多种语言 ...

  10. java泛型使用教程

    参考: java 泛型    Java泛型中E.T.K.V等的含义 一.Java泛型中E.T.K.V等的含义 E - Element (在集合中使用,因为集合中存放的是元素) T - Type(Jav ...