代码之余,将代码过程重要的一些代码段备份一下,如下的代码内容是关于Python从ftp服务器下载文件的的代码,希望能对小伙伴有用途。#coding=utf-8

'''

ftp自动下载、自动上传脚本,可以递归目录操作

'''

from ftplib import FTP

import os,sys,string,datetime,time

import socket

class MYFTP:

def __init__(self, hostaddr, username, password, remotedir, port=21):

self.hostaddr = hostaddr

self.username = username

self.password = password

self.remotedir = remotedir

self.port = port

self.ftp = FTP()

self.file_list = []

# self.ftp.set_debuglevel(2)

def __del__(self):

self.ftp.close()

# self.ftp.set_debuglevel(0)

def login(self):

ftp = self.ftp

try:

timeout = 300

socket.setdefaulttimeout(timeout)

ftp.set_pasv(True)

print u'开始连接到 %s' %(self.hostaddr)

ftp.connect(self.hostaddr, self.port)

print u'成功连接到 %s' %(self.hostaddr)

print u'开始登录到 %s' %(self.hostaddr)

ftp.login(self.username, self.password)

print u'成功登录到 %s' %(self.hostaddr)

debug_print(ftp.getwelcome())

except Exception:

print u'连接或登录失败'

try:

ftp.cwd(self.remotedir)

except(Exception):

print u'切换目录失败'

def is_same_size(self, localfile, remotefile):

try:

remotefile_size = self.ftp.size(remotefile)

except:

remotefile_size = -1

try:

localfile_size = os.path.getsize(localfile)

except:

localfile_size = -1

debug_print('localfile_size:%d remotefile_size:%d' %(localfile_size, remotefile_size),)

if remotefile_size == localfile_size:

return 1

else:

return 0

def download_file(self, localfile, remotefile):

if self.is_same_size(localfile, remotefile):

debug_print(u'%s 文件大小相同,无需下载' %localfile)

return

else:

debug_print(u' 下载文件 %s ... ...' %localfile)

#return

file_handler = open(localfile, 'wb')

self.ftp.retrbinary(u'RETR %s'%(remotefile), file_handler.write)

file_handler.close()

def download_files(self, localdir='./', remotedir='./'):

try:

self.ftp.cwd(remotedir)

except:

debug_print(u'目录%s不存在,继续...' %remotedir)

return

if not os.path.isdir(localdir):

os.makedirs(localdir)

debug_print(u'切换至目录 %s' %self.ftp.pwd())

self.file_list = []

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('..')

debug_print(u'返回上层目录 %s' %self.ftp.pwd())

def upload_file(self, localfile, remotefile):

if not os.path.isfile(localfile):

return

if self.is_same_size(localfile, remotefile):

debug_print(u'跳过[相等]: %s' %localfile)

return

file_handler = open(localfile, 'rb')

self.ftp.storbinary('STOR %s' %remotefile, file_handler)

file_handler.close()

debug_print(u'已传送: %s' %localfile)

def upload_files(self, localdir='./', remotedir = './'):

if not os.path.isdir(localdir):

return

localnames = os.listdir(localdir)

self.ftp.cwd(remotedir)

for item in localnames:

src = os.path.join(localdir, item)

if os.path.isdir(src):

try:

self.ftp.mkd(item)

except:

debug_print(u'目录已存在 %s' %item)

self.upload_files(src, item)

else:

self.upload_file(src, item)

self.ftp.cwd('..')

def get_file_list(self, line):

ret_arr = []

file_arr = self.get_filename(line)

if file_arr[1] not in ['.', '..']:

self.file_list.append(file_arr)

def get_filename(self, line):

pos = line.rfind(':')

while(line[pos] != ' '):

pos += 1

while(line[pos] == ' '):

pos += 1

file_arr = [line[0], line[pos:]]

return file_arr

def debug_print(s):

print s

if __name__ == '__main__':

timenow = time.localtime()

datenow = time.strftime('%Y-%m-%d', timenow)

# 配置如下变量

hostaddr = '211.15.113.45' # ftp地址

username = 'UserName' # 用户名

password = '123456' # 密码

port = 21 # 端口号

rootdir_local = 'E:/mypiv' # 本地目录

rootdir_remote = '/PIV' # 远程目录

f = MYFTP(hostaddr, username, password, rootdir_remote, port)

f.login()

f.download_files(rootdir_local, rootdir_remote)

timenow = time.localtime()

datenow = time.strftime('%Y-%m-%d', timenow)

logstr = u"%s 成功执行了备份n" %datenow

debug_print(logstr)

以上就是本文的全部内容,希望对大家的学习有所帮助。

python下载文件传到服务器_python实现从ftp服务器下载文件相关推荐

  1. 重新想象 Windows 8.1 Store Apps (91) - 后台任务的新特性: 下载和上传的新特性, 程序启动前预下载网络资源, 后台任务的其它新特性...

    原文:重新想象 Windows 8.1 Store Apps (91) - 后台任务的新特性: 下载和上传的新特性, 程序启动前预下载网络资源, 后台任务的其它新特性 [源码下载] 重新想象 Wind ...

  2. iphone文件访问ftp服务器,ipad ftp服务器 iPhone/iPad访问FTP服务器设置步骤

    ipad ftp服务器 iPhone/iPad访问FTP服务器设置步骤 2013-02-27 15:35:39 脚本之家 有时候出门在外需要用到电脑中的文件,但是却没有携带电脑或者U盘,那么该怎么办呢 ...

  3. sap 服务器 拷贝文件,本文示例如何使用SAP FTP Function将文件从应用服务器传输到另外一个FTP服务器上。...

    本文示例如何使用SAP FTP Function将文件从应用服务器传输到另外一个FTP服务器上. DATA: BEGIN OF ig_ftp_result OCCURS 0, line(100), E ...

  4. miniftp服务器技术文档,ftp服务器 mini

    ftp服务器 mini 内容精选 换一换 通过FTP或SFTP连接,可以对FTP或SFTP服务器抽取或加载文件,支持CSV.二进制和JSON格式.FTP和SFTP的连接参数相同. 通过FTP或SFTP ...

  5. ftp服务器不显示缩略图,ftp服务器不显示缩略图

    ftp服务器不显示缩略图 内容精选 换一换 节点是指接入到平台的计算资源,包括虚拟机.物理机等.用户需确保所在项目节点资源充足,若节点资源不足,会导致创建工作负载等操作失败.已创建至少一个集群,请参见 ...

  6. Ubuntu Server搭建FTP服务器(2) --本地用户FTP服务器架设

    Ubuntu Server搭建FTP服务器(2) --本地用户FTP服务器架设 参考:ubuntu中文wiki百科,网址:wiki.ubuntu.org.cn 环境:Ubuntu 9.04 Serve ...

  7. 为什么ftp服务器不显示文件夹,FTP服务器进入不显示文件夹

    FTP服务器进入不显示文件夹 内容精选 换一换 版本升级后,节点管理页面显示节点状态为版本不匹配.升级过程中输入错误的节点服务器认证信息,导致节点升级失败.在Web服务器上执行版本不匹配节点的升级脚本 ...

  8. winxp系统做服务器,winxp系统做ftp服务器

    winxp系统做ftp服务器 内容精选 换一换 简要介绍Emacs是可扩展的.可定制的.自我记录的实时显示编辑器.其核心是Emacs Lisp的解释器,它是一种Lisp编程语言的方言,带有扩展以支持文 ...

  9. python程序发布到阿里云云服务器_Python实现阿里云服务器里的文件上传与下载

    Python实现阿里云服务器里的文件上传与下载 018.4.15 背景: 老实说,因为现实的各种原因造成电脑换来换去是可能出现的事情,但是电脑能换,电脑里的环境却不能换.我就曾在三个电脑里各自安装了虚 ...

最新文章

  1. C++动态链接库dll及静态链接库lib制作及使用教程
  2. 基于Struts2.3.x+Spring3.2.x+Hibernate4.2.x+EasyUI1.3.4+Maven架构的示例程序
  3. “智能微尘”:助推物联网应用的关键
  4. [css] 简述你对BFC规范的理解
  5. 模拟退火算法求解TSP问题
  6. 为什么程序员更喜欢用google搜索? 因为正经!
  7. 网线重新插拔后恢复正常_14日科技精选:路由器经常掉线,必须重新插拔网线才能上网。什么原因?...
  8. Keras官方中文文档:Keras安装和配置指南(Windows)
  9. 如何使用sqlpackage和PowerShell将示例bacpac文件导入到Azure SQL数据库
  10. 深度学习之GAN对抗神经网络
  11. js基础---字符串方法
  12. AeroSpike踩坑手记1:Architecture of a Real Time Operational DBMS论文导读
  13. Android ListView 技巧 (一) Android ListView Header
  14. c语言输出100以内的素数存放数组中,c语言素数(c语言输出100以内素数)
  15. 单细胞多组学联合应用
  16. 46泰勒中值定理的常规证明
  17. jQuery——淘宝购物车结算页面demo
  18. cocos2d-x 使用位图工具制作 fnt字体
  19. 树莓派4B安装tensorflow2.0.0和keras2.3.1
  20. textarea去除红色波浪线

热门文章

  1. TOP100summit分享实录 | 数字化三支柱:企业数字化转型的众妙之门
  2. Autoencoders
  3. 2058(等差求和)
  4. 10.11 UiPath如何安全的保存账号和密码
  5. 现在大家都在用的钢琴键盘模拟器好用吗?
  6. 同时删除多个 PPT 文档中间几页
  7. 大白菜装win10专业版启动u盘制作教程
  8. 基于CenOS7.9安装Ambari2.7.4.0+HDP3.1.4.0大数据平台
  9. 考试反思计算机专业,计算机考试成绩分析与总结
  10. ESP32 学习笔记(九)SPI - SPI Slave