首页 > 代码库 > python实现ftp上传下载文件
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上传下载文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。