#-*-coding:utf8 -*-
#!/usr/bin/env python
from ftplib import FTP
import time
import os
import logging
import logging.handlers
class Log():
def __init__(self):
pass
''' 记录日志到文件 '''
def logger(self,logfile):
logger = logging.getLogger()
#handler = logging.FileHandler(logfile) #记录日志到单个文件
#rhandler = logging.handlers.RotatingFileHandler(filename=logfile,mode='a',maxBytes=1024*1024*1,backupCount=10) #记录日志到文件
thandler = logging.handlers.TimedRotatingFileHandler(filename=logfile,when='D',interval=1,backupCount=10)#保留十天的日志
formatter = logging.Formatter('[%(levelname)s] \t %(asctime)s %(filename)s %(filename)s %(message)s')
thandler.setFormatter(formatter)
logger.addHandler(thandler)
logger.setLevel(logging.NOTSET)
return logger
log = Log()
logger = log.logger("c://log/temp.log")
logger.info("Start Log log")
class HandleFtp():
def __init__(self):
pass
''' check network status result==1 : network is not ok result==0: network is ok '''
def checkNetwork(self,netaddress):
#处理 Packets: Sent = 4, Received = 2, Lost = 2 (50% loss), 状况
time.sleep(2)
result = os.system('ping '+netaddress)
return result
def login(self,ip,port,loginame,passwd,dir):
ftp=FTP()
#ftp.set_debuglevel(2) #打开调试级别2,显示详细信息
logger.info("+++++++++++++++++++ Ftp Server Info +++++++++++++++++")
logger.info(" ftp server's ip "+ip)
logger.info(" ftp server's port "+str(port))
logger.info(" ftp server's loginame "+loginame);
logger.info(" ftp server's passwd "+passwd)
logger.info(" ftp server's dir "+dir)
logger.info("+++++++++++++++++++ Ftp Server Info +++++++++++++++++")
ftp.connect(ip,port) #连接
ftp.login(loginame,passwd) #登录,如果匿名登录则用空串代替即可
#print ftp.getwelcome() #显示ftp服务器欢迎信息
ftp.cwd(dir) #选择操作目录
self.bufsize = 1024 #设置缓冲块大小
return ftp
def handleData(self,ftp,ftpaddress,port,loginame,passwd,dir):
while(True):
if self.checkNetwork(ftpaddress) == 1:
logger.error("network happens errors ftpaddress "+ftpaddress)
time.sleep(10 * 1)
else:
print "++++++++++++++++++++++++++++++++"
print ftp
try:
filelist = ftp.nlst()
except Exception:
pass
finally:
ftp = self.login(ftpaddress, port,loginame, passwd, dir)
print ftp.nlst()
for file in filelist:
filename=file
filename1 = "c:\\temp\\"+filename
print filename
print filename1
try:
file_handler = open(filename1,'wb') #以写模式在本地打开文件
except Exception:
logger.exception(" open file "+filename1+" hanppen exception"+Exception)
try:
ftp.retrbinary('RETR '+filename,file_handler.write,self.bufsize) #接收服务器上文件并写入本地文件
except Exception:
logger.exception(" get data "+filename+" happen exception "+Exception)
filename1 = ""
filename = ""
try:
file_handler.close()
except Exception:
logger.exception("close file "+filename+" happen exception "+Exception )
time.sleep(10);
def quit(self,ftp):
ftp.quit() #退出ftp服务器
#ftp.set_debuglevel(0) #关闭调试
if __name__ == "__main__":
ftp = HandleFtp()
ftpl = ftp.login('10.232.75.46', 21,'anonymous', '', '/')
ftp.handleData(ftpl,'10.232.75.46', 21,'anonymous', '', '/')