码迷,mamicode.com
首页 > 编程语言 > 详细

python实现ftp上传下载文件

时间:2017-02-27 15:57:22      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:download   下载文件   上传文件   change   python   

#!/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上传下载文件

标签:download   下载文件   上传文件   change   python   

原文地址:http://78799999.blog.51cto.com/9500788/1901656

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!