# coding=UTF-8
import os,sys,ftplib,random,time
from datetime import datetime,date
backpath = '/data/xxxx'
cur_date = date.strftime(datetime.today(),'%Y-%m-%d')
class vssbackup:
def __init__(self):
self.sep = os.sep
self.allfile = []
self.file_dict = {}
self.ftp_addr = 'xxxxxx'
self.ftp_user = 'xxxx'
self.ftp_pass = 'xxxx'
self.cur_date = date.strftime(datetime.today(),'%Y-%m-%d')
def getfile(self,path):
for i in os.listdir(path):
if os.path.isdir(path+self.sep+i):
self.getfile(path+self.sep+i)
else:
self.allfile.append(path+self.sep+i)
def calc_md5(self):
if sys.version[0:3] == '2.4':
import md5 as hashlib
else:
import hashlib
for file in self.allfile:
file_basename = os.path.basename(file)
calcer = hashlib.md5()
calcer.update(file_basename)
md5_value = calcer.hexdigest()
filelist = open('./filelist_'+self.cur_date+'.ini','ab')
filelist.write('%s %s\n' % (file,md5_value))
filelist.close()
self.file_dict[file] = md5_value
def ftpput(self,path):
ftp = ftplib.FTP()
ftp.connect(self.ftp_addr)
ftp.login(self.ftp_user,self.ftp_pass)
for file in self.allfile:
file_handler = open(file,'rb')
ftp_filename = file[len(os.path.dirname(path.rstrip('/'))):]
dict_filename = self.file_dict[file]
ftp_dirname = os.path.dirname(ftp_filename).strip('/').split('/')
ftp_basename = os.path.basename(file)
for dir in ftp_dirname:
try:
ftp.mkd(dir)
ftp.cwd(dir)
except:
ftp.cwd(dir)
try:
a = ftp.nlst(dict_filename)
if len(a) == 0:
print 'uploading.....'+dict_filename
ftp.storbinary('STOR %s' %dict_filename,file_handler,4096)
file_handler.close()
ftp.cwd('/')
except:
print 'uploading.....'+dict_filename
ftp.storbinary('STOR %s' %dict_filename,file_handler,4096)
file_handler.close()
ftp.cwd('/')
time.sleep(0.5)
ftp.close()
if __name__ == '__main__':
for path in backpath.split(','):
a = vssbackup()
a.getfile(path)
a.calc_md5()
a.ftpput(path)