備份主目錄

就是書上的習題…


#!/usr/bin/python2.7
# coding=utf-8
# Filename: backupmyhome.py

print '此腳本將在 /home 下創建備份,需要root權限,請確認輸入了 sudo !'
toor = raw_input('確認已取得root權限請按回車繼續,按Ctrl+C退出:')
print ''
#通過這種土鱉的方式,我可以將輸出結果變得整潔一點- -

if len(toor) == 0:

    import os
    import time

    source = ['~/']
    target_dir = '/home/backup'
    today = target_dir + time.strftime('%Y%m%d')
    now = time.strftime('%H%M%S')
    comment = raw_input('輸入一個註釋(按回車略過此項):')
    print ''

    if len(comment) == 0:
        target = today + os.sep + now + '.tar.gz'
    else:
       target = today + os.sep + now + '_' + comment.replace(' ','_') + '.tar.gz'

    if not os.path.exists(today):
        os.mkdir(today)
        print '成功創建了文件夾', today

    tar_command = 'tar -cvzf %s %s' % (target, ' '.join(source))
    #有誰能告訴我怎麼使用tarfile庫麼?另外,參數使用了-z,需要安裝gzip
    print '正在備份,根據文件夾大小將消耗一定的時間,請稍候……'
    print ''

    if os.system(tar_command) == 0:
        print ''
        print '成功創建備份於', target
    else:
        print ''
        print '備份失敗!'

else:
    print '未取得root權限,請重試!'

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章