备份主目录

就是书上的习题…


#!/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权限,请重试!'

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