python实现ftp上传下载文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实现ftp上传下载文件相关的知识,希望对你有一定的参考价值。
#!/usr/bin/env python # encoding: utf-8 __author__ = "pwy" ‘‘‘ 上传:上传文件并备份到其他目录 下载:下载文件,并删除远端文件 ‘‘‘ from ftplib import FTP from time import sleep import os,datetime,logging from shutil import move HOST = "192.168.1.221" USER = "sxit" PASSWORD = "1qaz!QAZ" #PORT = "" #Upload the file, change the directory remotedir = "/home/test/" localdir = "/home/sxit/object/" bakdir = "/home/sxit/bak" #Download the file, change the directory Remoredir = "/home/sxit/object1/" Localdir = "/root/ftp-logging" LOGFILE = datetime.datetime.now().strftime(‘%Y-%m-%d‘)+‘.log‘ logging.basicConfig(level=logging.INFO, format=‘%(asctime)s %(filename)s %(levelname)s %(message)s‘, # datefmt=‘%a, %d %b %Y %H:%M:%S‘, filename= LOGFILE, filemode=‘a‘) logging.FileHandler(LOGFILE) class CLASS_FTP: def __init__(self,HOST,USER,PASSWORD,PORT=‘21‘): self.HOST = HOST self.USER = USER self.PASSWORD = PASSWORD self.PORT = PORT self.ftp=FTP() self.flag=0 # 0:no connected, 1: connting def Connect(self): try: if self.flag == 1: logging.info("ftp Has been connected") else: self.ftp.connect(self.HOST,self.PORT) self.ftp.login(self.USER,self.PASSWORD) # self.ftp.set_pasv(False) self.ftp.set_debuglevel(0) self.flag=1 except Exception: logging.info("FTP login failed") def Up_load(self,remotedir,localdir,bakdir): try: self.ftp.cwd(remotedir) for i in os.listdir(localdir): if i.endswith(‘.txt‘): file_handler = open(i,‘rb‘) self.ftp.storbinary(‘STOR %s‘ % i,file_handler) logging.info("%s already upload ."%i) try: if os.path.isdir(bakdir): move(i,bakdir) logging.info("%s move to %s ." % (i,bakdir)) else: print "Move the file FAILED" logging.info("Move the %s to %s FAILED!"%(i,bakdir)) except Exception: logging.info("ftp delete file faild !!!!!") file_handler.close() # self.ftp.quit() except Exception: logging.info("Up_load failed") def Down_load(self,Remoredir,Localdir): try: self.ftp.cwd(Remoredir) for i in self.ftp.nlst(): if i.endswith(‘.NET‘): #match file file_handler = open(i,‘wb‘) self.ftp.retrbinary(‘RETR %s‘ % i,file_handler.write) logging.info("%s already down ."%i) try: self.ftp.delete(i) logging.info("%s already deleted!"%i) except Exception: logging.info("ftp delete file faild !!!!!") file_handler.close() #self.ftp.quit() except Exception: logging.info("Down_load failed") if __name__ == ‘__main__‘: ftp = CLASS_FTP(HOST,USER,PASSWORD) while True: ftp.Connect() # ftp.Down_load(Remoredir,Localdir) ftp.Up_load(remotedir,localdir,bakdir) sleep(30)
本文出自 “python学屠兵” 博客,请务必保留此出处http://78799999.blog.51cto.com/9500788/1901656
以上是关于python实现ftp上传下载文件的主要内容,如果未能解决你的问题,请参考以下文章
Python-Socketserver实现FTP,文件上传下载
Python操作FTP服务器实现文件和文件夹的上传与下载,python清理ftp目录下的所有文件和非空文件夹
Python 连接FTP服务器并实现文件夹下载实例演示,python区分ftp目录下文件和文件夹方法,ftp目录下包含中文名问题处理
Python 连接FTP服务器并实现文件夹下载实例演示,python区分ftp目录下文件和文件夹方法,ftp目录下包含中文名问题处理