用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. 0007-20180403-python-自动化基础学习000--while-if 循环实操

    python-自动化基础学习000 Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64 ...

  2. firefox 实现web交互机器人

    现在仅有火狐浏览器可以这样操作 -- Filefox 下面是项目目录 -- 前端页面 -- html <!DOCTYPE html> <html lang="en" ...

  3. openGL学习----相机

    0.参考:https://learnopengl-cn.github.io/01%20Getting%20started/09%20Camera/ 0.0其实相机就是搞清楚cameraPos,came ...

  4. Generative Adversarial Nets

    1. 基本思想 两个模型: 判别器:预测从生成器生成的样本的概率 生成器:生成样本时,最大化使得判别器发生错误的概率 最后得到唯一解:使得生成器生成的样本输入到判别器中,得到的概率全是1/2.    ...

  5. 02: OpenStack

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

  6. topcoder srm 585 div1

    problem1 link 最优的策略就是从最低下一层开始,每两层的三个节点的子树都可以用一次遍历覆盖. problem2 link 从大到小依次放置每一种数字,并记录已经放置的数字一共有多少个$m$ ...

  7. 【常见错误】Quartz常见错误

    1.集群之后把其中一个Quartz服务停了,其他的也不接手工作 问题描述 集群之后,A节点执行了大多数任务,B节点大部分时间处于空闲,停掉A节点,B节点也不会接手工作. 解决方式 修改Quartz的配 ...

  8. C# 在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke

    http://www.cnblogs.com/fish124423/archive/2012/10/16/2726543.html 在Invoke(....)之前加上1 this.components ...

  9. UVA1400 "Ray, Pass me the dishes!"

    思路 线段树维护最大子段和,只不过这题还要维护左右端点 还是维护pre,suf,sum,ans,只不过每个再多出一个维护端点的变量即可 注意多解讨论的大于号和大于等于号 代码 #include < ...

  10. C/C++.判断文件是否存在(_access)

    1. int _access(char* path,int mode)头文件<io.h>功能:确定文件或文件夹的访问权限.如果指定的存取方式有效,则函数返回0,否则函数返回-1. 参数pa ...