用python 造了一個輪子:
- 在服務器上自動拷貝文件到指定目錄,在覆蓋前自動備份舊的文件;
- 這個腳本寫得很簡單只是檢驗文件是否一致,未做新舊文件的判斷,如有其他需求請自行修改;
- 同時備份發佈文件到指定目錄;
- 發佈完文件後自動刪除發佈目錄;
- 如要過濾發佈文件的類型,請自行添加一行代碼;
這個腳本需要一個配置文件,配置的格式如下:
[publish]
source=d:\update
target=d:\website
bakup=d:\backup
publish=d:\publish
import ConfigParser,io,sys,os
'''
Date: 2013.08.09
Author: Sean Pu
Ver: 0.2
Declare:
Maybe some bugs can not find by local test,after u update new files ,u find it; At that time,u need recover the old files immediately.
This script help u update the new files and backup the old files.
This script can be use in many OS that support python.
Before run this script,pls config the file :update.conf
'''
import filecmp
import datetime
import shutil
#fortmat print data
def Pl (str):
n=datetime.datetime.now()
print n.strftime('%Y-%m-%d %H:%M:%S '),str
#delete file and dir,the follow function copy from internet
def delete_file_folder(src):
if os.path.isfile(src):
try:
os.remove(src)
except:
pass
elif os.path.isdir(src):
for item in os.listdir(src):
itemsrc=os.path.join(src,item)
delete_file_folder(itemsrc)
try:
os.rmdir(src)
except:
pass
def ChkF(spath,tpath,bpath,ppath):
if os.path.exists(spath)==False:
Pl('there is no dir:'+spath+',pls check it.')
return
sf=os.listdir(spath)
for f in sf:
s_child_path=spath+"\\"+f
t_child_path=tpath+"\\"+f
b_child_path=bpath+"\\"+f
p_child_path=ppath+"\\"+f
if os.path.isdir(s_child_path):
if os.path.exists(t_child_path)==False:
os.makedirs(t_child_path)
if os.path.exists(p_child_path)==False:
os.makedirs(p_child_path)
ChkF(s_child_path,t_child_path,b_child_path,p_child_path)
else:
if os.path.exists(t_child_path):
#if file not same,backup and copy file
if filecmp.cmp(s_child_path,t_child_path)==False:
Pl("bak:"+bpath)
#Pl(b_child_path)
if os.path.exists(bpath)==False:os.makedirs(bpath)
#bakup file first ,then copy new file to target dir
shutil.copy(t_child_path,b_child_path)
shutil.copy(s_child_path,t_child_path)
shutil.copy(s_child_path,p_child_path)
else:
Pl(b_child_path)
shutil.copy(s_child_path,t_child_path)
shutil.copy(s_child_path,p_child_path)
#shutil.rmtree(s_child_path)
delete_file_folder(s_child_path)
#Get config file
config=ConfigParser.RawConfigParser()
config.read("update.conf")
sourceDir=config.get('publish','source')
targetDir=config.get('publish','target')
bakupDir=config.get('publish','bakup')
pubDir=config.get('publish','publish')
n=datetime.datetime.now()
n=n.strftime('%Y%m%d')
bakupDir=bakupDir+"\\"+n
pubDir=pubDir+"\\"+n
if os.path.exists(bakupDir)==False:os.mkdir(bakupDir)
if os.path.exists(pubDir)==False:
os.mkdir(pubDir)
print sourceDir,targetDir,bakupDir,pubDir
Pl ('begin update file and dir in : '+sourceDir+'')
if os.path.exists(sourceDir)==False:
Pl('there is no dir:'+sourceDir+',pls check it.')
exit()
ChkF(sourceDir,targetDir,bakupDir,pubDir)
exit();