一、可行性分析:
一般從經濟、技術、社會、人四個方向分析。
二、需求分析:
需求分析就是需要實作哪些功能,這個很明了-檔案備份
幾個問題:
我們的備份位置?
什麼時間備份?
備份哪些檔案?
怎麼樣存儲備份(檔案類型)?
備份檔案的名稱?(需要通俗明了,一般是以目前時間命名)
三、實施過程:
方案一:
#!/usr/lib/env python
import os
import time
backlist=['/etc','/root']
to='/mnt/'
target=to+time.strftime('%Y%m%d%H%M%S')+'.tar.gz'
gz_command="tar -czf %s %s"%(target,' '.join(backlist))
if os.system(gz_command)==0:
print 'successfull'
else:
print 'failed'
改進方案二:
方案二主要是考慮到多建日期子目錄,這樣更加明了
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
target = today + os.sep + now + '.zip'
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
注意:os.sep代表/或者\
改進方案三:可以給備份檔案名稱加注解:
#!/usr/bin/env python
source=['/var/log','/etc/ssh']
target='/mnt/'
today=target+time.strftime('%Y%m%d')
now=time.strftime('%H%M%S')
comment=raw_input('pls input the comment-->')
if len(comment)==0:
target1=today+os.sep+now+'.tar.gz'
target1=today+os.sep+now+'_'+comment.replace(' ','_')+'.tar.gz'
os.mkdir(today)
comm="tar -czf %s %s"%(target1,' '.join(source))
if os.system(comm)==0:
print 'successfull'
print 'failed'
方案四:增加互動性
最理想的建立這些歸檔的方法是分别使用zipfile和tarfile子產品。它們是Python标準庫的一部分,可以
供你使用。使用這些庫就避免了使用os.system這個不推薦使用的函數。這個不推薦的原因今天問了下同僚:
os.system是将内容傳給c寫的system函數,由對應系統處理,是以經常會遇到一些空格和引号的問題哈
而且c的system()本身就有一些限制,不更改,是以大家一般習慣于簡單的可以用os.system,複雜的用subprocess.popen。
另外一方面可以通過互動式輸入需要備份的目錄然後用list的extend方法加到清單中去。這裡我是直接把sys.argv清單的值全部指派給一個空清單。
import sys
backlist=[]
backlist=sys.argv[1:]
if len(backlist)==0:
backlist.append('/root')
today=to+time.strftime('%Y%m%d')
os.mkdir(today)
print 'Successfully created directory', today
comment=raw_input('pls input the comment for your backup files-->')
target=today+os.sep+now+'.tar.gz'
target=today+os.sep+now+'-'+comment.replace(' ','_')+'.tar.gz'
print os.sep
'
本文轉自chenzudao51CTO部落格,原文連結:http://blog.51cto.com/victor2016/1875945 ,如需轉載請自行聯系原作者