#!/bin/env Python
import os,time,ftplib,string
import glob,sys
import os.path
home='/root/backcvs' #本地保存文件目錄
ftphost='192.168.220.10' #ftp備份服務(wù)器
ftpuser='qa' #ftp登陸用戶名
ftppass='qa' #ftp登陸密碼
ftppassmode=1 #ftp模式 port 0 passive 1
ftpdir='backcvs' #ftp上存放備份的目錄
cvsdir='/cvshome' #cvs代碼存放目錄
data=time.strftime('%y-%m-%d')
cvstarfile="cvsroot"+data+".tgz"
global fd
if not os.path.isdir(home):
os.mkdir(home)
os.chdir(home)
lastfilelen = os.path.getsize(glob.glob("*.tgz")[-1])
cmd = "tar zcvf "+cvstarfile+" "+cvsdir
if (os.system(cmd))!=0:
print "tar file faild! cmd:[%s]"%(cmd)
sys.exit(1)
newfilelen = os.path.getsize(cvstarfile)
print "new:%d,old:%d"%(newfilelen,lastfilelen)
if (newfilelen == lastfilelen):
print "file size not change! exit!"
sys.exit(0)
print "while upload file:%s,size:%d"%(cvstarfile,newfilelen)
if os.getcwd()==home:
ftp=ftplib.FTP(ftphost,ftpuser,ftppass)
ftp.set_pasv(ftppassmode)
ftp.cwd(ftpdir)
paths=ftp.nlst('cvsroot*')
print paths
if len(paths) > 5:
ftp.delete(paths[0])
os.remove(paths[0])
fd = open(cvstarfile, 'rb')
ftp.storbinary('STOR%s' % os.path.basename(cvstarfile), fd)
fd.close()
ftp.quit()
然后在crontab里面中定義備份時(shí)間定時(shí)啟動(dòng)的命令可以了!
0 0 0 ? * SUN Python /root/backcvs/backcvs.py