用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. LEFT JOIN、RIGHT JOIN、INNER JOIN、FULL JOIN 使用

    select * from t_class_info as c; id   gradeid  classid  year        createtime                       ...

  2. html5,dom操作1

    <body> <script>function hwd(){ var bb=document.getElementById('bt');// alert(bb.innerHTM ...

  3. Cycle (KMP + hash)

    题意:给你2个串,让你判断2个字符串的前缀是否满足首尾连接形成的环是不是一样的. 思路:我们需要提前知道的是满足条件的前缀一定满足 strA = str1 + str2, strB = str2 + ...

  4. vue项目初始化时npm run dev报错webpack-dev-server解决方法

    vue项目初始化时npm run dev报错webpack-dev-server解决方法 原因:这是新版webpack存在的BUG,卸载现有的新版本webpack,装老版本就好webpack-dev- ...

  5. 每天一个Linux命令 10

    文件处理命令:ln命令名称:ln 命令英文原意:link语法: ln -s [原文件] [目标文件] -s 创建软连接功能描述:生成链接文件 #ln -s /etc/issue /tmp/issue. ...

  6. videojs+hls+rtmp流媒体播放

    前言:刚接触前端,小白一个,如有出错,请指正,谢谢! 注:视频格式可以分为适合本地播放的本地影像视频和适合在网络中播放的网络流媒体影像视频两大类. 一.互联网网络流媒体简介 HTTP stream是各 ...

  7. CentOS7查看systemctl 控制的服务的相关配置

    例如,启动配置文件 [root@Docker_Machine_192.168.31.130 ~]# systemctl show --property=FragmentPath docker Frag ...

  8. elasticsearch best_fields most_fields cross_fields从内在实现看区别——本质就是前两者是以field为中心,后者是词条为中心

    1.最佳字段(Best fields):: 假设我们有一个让用户搜索博客文章的网站(允许多字段搜索,最佳字段查询),就像这两份文档一样: PUT /my_index/my_type/1 { " ...

  9. jQuery安装和语法

    jQuery是一个JavaScript函数库,可实现HTML元素选取及操作.CSS 操作.HTML事件函数.JavaScript特效和动画.HTML DOM遍历和修改.AJAX等功能. 在html中引 ...

  10. Linux cached过高问题

    1. cached主要负责缓存文件使用, 日志文件过大造成cached区内存增大把内存占用完 . Free中的buffer和cache:(它们都是占用内存):buffer : 作为buffer cac ...