# encoding:utf-8

from ftplib import FTP
import os
import sys

_XFER_FILE = 'FILE'
_XFER_DIR = 'DIR'

class FtpClient(object):
def __init__(self):
self.ftp = None

def __del__(self):
pass

def setFtpParams(self, ip, uname, pwd, port=21, timeout=60):
self.ip = ip
self.uname = uname
self.pwd = pwd
self.port = port
self.timeout = timeout

def initEnv(self):
if self.ftp is None:
self.ftp = FTP()
print '### connect ftp server: %s ...' % self.ip
self.ftp.connect(self.ip, self.port, self.timeout)
self.ftp.login(self.uname, self.pwd)
print self.ftp.getwelcome()
self.ftp.set_pasv(False)

def clearEnv(self):
if self.ftp:
self.ftp.close()
print '### disconnect ftp server: %s!' % self.ip
self.ftp = None

def uploadDir(self, localDir='./', remoteDir='./'):
if not os.path.isdir(localDir):
return
self.ftp.cwd(remoteDir)
for file in os.listdir(localDir):
source = os.path.join(localDir, file)
if os.path.isfile(source):
self.uploadFile(source, file)
elif os.path.isdir(source):
try:
self.ftp.mkd(file)
except:
sys.stderr.write('The dir is exists %s' % file)
self.uploadDir(source, file)
self.ftp.cwd('..')

def uploadFile(self, localPath, remotePath='./'):
if not os.path.isfile(localPath):
return
print (' upload %s to %s' % (localPath, remotePath))
self.ftp.storbinary('STOR ' + remotePath, open(localPath, 'rb'))

def __filetype(self, src):
if os.path.isfile(src):
index = src.rfind('/')
# if the src not contains /
if index == -1:
index = src.rfind('/')
return _XFER_FILE, src[index + 1:]
elif os.path.isdir(src):
return _XFER_DIR, ''

def upload(self, lacaldir, remoteDir="./"):
filetype, filename = self.__filetype(lacaldir)

self.initEnv()
if filetype == _XFER_DIR:
self.srcDir = lacaldir
self.uploadDir(self.srcDir, remoteDir)
elif filetype == _XFER_FILE:
self.uploadFile(lacaldir, filename)
self.clearEnv()

def download_file(self, localfile, remotefile):

self.debug_print('>>>>>>>>>>>>下载文件 %s ... ...' % localfile)
# return
with open(localfile, 'wb') as f:
self.ftp.retrbinary('RETR %s' % (remotefile), f.write)

def download_files(self, localDir='./', remoteDir='./'):
"""
从远程目录下,下载所有的文件并创建对应的目录
:param localdir: 本地文件夹
:param remotedir: 远程服务文件夹
:return:
"""
try:
self.ftp.cwd(remoteDir)
print self.ftp.pwd()
except:
self.debug_print(u'目录%s不存在,继续...' % remoteDir)
return
if not os.path.isdir(localDir):
os.makedirs(localDir)
self.debug_print(u'切换至目录 %s' % self.ftp.pwd())
self.file_list = []
#
# self.ftp.dir(self,*args) List a directory in long form
# 最后一个参数为回调函数,前面的不为空的参数,会跟list 组合成command
# 默认列出当前目录下的内容
#
self.ftp.dir(self.get_file_list)
remotenames = self.file_list
# print(remotenames)
# return
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('..')
self.debug_print('返回上层目录 %s' % self.ftp.pwd())

def get_file_list(self, line):
"""

:param lines: ftp.dir() provide the line
:return: return the file list ,that get file name from line
"""
# ret_arr = []
file_arr = self.get_filename(line)
if file_arr[1] not in ['.', '..']:
self.file_list.append(file_arr)

def debug_print(self, s):
print s

def get_filename(self, line):
"""
line maybe :-rw-r--r-- 1 501 501 320294 Aug 24 05:08 1.d2dc00a98a6eee589f2e.chunk.js
:param line:
:return: return the first word of line and get the file name.
"""
pos = line.rfind(':')
while (line[pos] != ' '):
pos += 1
while (line[pos] == ' '):
pos += 1
file_arr = [line[0], line[pos:]]
return file_arr

if __name__ == '__main__':
localdir = r"d:\mysql\www"
# remoteDir = r"/"
xfer = FtpClient()
xfer.setFtpParams('', 'tny', '')
xfer.initEnv()
xfer.uploadDir(localDir=localdir)

python ftp批量上传文件下载文件的更多相关文章

  1. Python基于Python实现批量上传文件或目录到不同的Linux服务器

    基于Python实现批量上传文件或目录到不同的Linux服务器   by:授客 QQ:1033553122 实现功能 1 测试环境 1 使用方法 1 1. 编辑配置文件conf/rootpath_fo ...

  2. linux下常用FTP命令 上传下载文件【转】

    1. 连接ftp服务器 格式:ftp [hostname| ip-address]a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码,分别输入用户名和相应密码 ...

  3. linux ftp批量上传和下载文件

    一.登录ftp 输入 ftp 192.168.1.111 输入用户名:ftpuser 输入密码:aaa123 二.转到目标目录 输入:cd   test   ----test为文件夹 三.批量上传 输 ...

  4. Linux 终端访问 FTP 及 上传下载 文件

    今天同事问我一个问题,在Linux 下访问FTP,并将文件上传上去. 我之前一直是用WinSCP工具的. 先将文件从linux copy到windows下,然后在传到ftp上.google 一下. 方 ...

  5. Linux 终端訪问 FTP 及 上传下载 文件

    今天同事问我一个问题,在Linux 下訪问FTP,并将文件上传上去. 我之前一直是用WinSCP工具的. 先将文件从linux copy到windows下,然后在传到ftp上. google 一下. ...

  6. Linux 终端访问 FTP 及 上传下载 文件[转]

    1.      Linux 终端连接FTP [oracle@Dave ~]$ ftp 10.85.7.97 Connected to 10.85.7.97. 220 Serv-U FTP Server ...

  7. 使用批处理文件在FTP服务器 上传下载文件

    1.从ftp服务器根目录文件夹下的文件到指定的文件夹下 格式:ftp -s:[配置文件] [ftp地址] 如:ftp -s:c:\vc\ftpconfig.txt   192.168.1.1 建立一个 ...

  8. Yii 图片FTP批量上传 并生成缩略图

    图片批量上传,前台使用 uploadify.swf,这个就不介绍了.这里使用两个扩展,一个是FTP上传的扩展,还有一个是生成缩略图的扩展地址:http://www.yiiframework.com/e ...

  9. shell通过ftp实现上传/下载文件

    直接代码,shell文件名为testFtptool.sh: #!/bin/bash ########################################################## ...

随机推荐

  1. windows10远程桌面连接身份验证错误:函数不受支持,这可能是由于 CredSSP 加密 Oracle 修正

    前言:因windows10的更新,最近很多朋友会遇到mstsc远程连接桌面报错: windows10企业版解决方式: 按“win+R”,运行 gpedit.msc, 找:“计算机配置”->“管理 ...

  2. ZHS16GBK的数据库导入到字符集为AL32UTF8的数据库

    字符集为ZHS16GBK的数据库导入到字符集为AL32UTF8的数据库  相信大家都对字符集有相当的了解了,废话就不多说了!直接步入正题:这里主要是测试含有 汉字的数据从ZHS16GBK的数据库导入到 ...

  3. js数组中随机选取一个数值!!

    var arr = ["太阳光大","成功是优点的发挥","不要小看自己", "口说好话","手心向下是助人& ...

  4. 核主成分分析方法(KPCA)怎么理解?

    先回顾下主成分分析方法.PCA的最大方差推导的结论是,把数据投影到特征向量的方向后,方差具有极大值的.假如先把数据映射到一个新的特征空间,再做PCA会怎样?对于一些数据,方差会更好地保留下来.而核方法 ...

  5. flutter 本地存储 (shared_preferences)

    Flutter本地存储 和Android.Ios类似,Flutter也支持Preferences(Shared Preferences and NSUserDefaults) .文件.和Sqlite3 ...

  6. HDU 2174 Bridged Marble Rings

    题目:Bridged Marble Rings 链接:http://acm.hdu.edu.cn/showproblem.php?pid=2174 题意:如图,要把所有灰色球移动到上圈,每次操作可以转 ...

  7. MySQL 5.6 for Windows 解压缩版配置安装 和 MySQL 数据库的安装和密码的设定

    https://jingyan.baidu.com/article/f3ad7d0ffc061a09c3345bf0.html https://jingyan.baidu.com/article/09 ...

  8. Warning: Using a password on the command line interface can be insecure.

    [root@qttc ~]# /usr/local/mysql/bin/mysqldump  -uroot -proot db > bak.sqlWarning: Using a passwor ...

  9. axios拦截http拦截

    一,判断登录页面 const routes = [ { path: '/', name: '/', component: Index }, { path: '/repository', name: ' ...

  10. 2019-04-09 SpringBoot+Druid+MyBatis+Atomikos 的多数据源配置

    前面部分是网上找的,我按照网上写的把自己搭建的过程展示一次 1.引入依赖 目前项目本来使用到了Mybatis plus(在自己的Mapper接口中继承BaseMapper获得基本的CRUD,而不需要增 ...