您的位置:首页 > 编程语言 > Python开发

Python 备份脚本

2014-09-16 15:42 302 查看
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Filename: bak_ws.py

import os
import time
import sys

# 1, The files and directories to be backed up are specified in a list
# source = ['/home/my_prog','/usr/local/mydata/']
print '-' * 32
source=[]
print 'The command line arguments are: '
for i in sys.argv:
print i
if i == sys.argv[0]:
continue
source.append(i)
print '-' * 32
# check input, if error app exit
if len(source) == 0:
print '''You should input the files or directories, like
python bak.py /home/my_prog /usr/local/mydata/ ...'''
exit()
else:
print 'Some files or directorier will be saved into .tar.gz format:'
print source
# If you are using Windows, use
# source=[r'c:/Documents', r'd:/work'] or
# something like that
# 2, The backup must be stored in a main backup directory
# Remember to change this to what you will be using
target_dir = '/data/backup/'
# 判断目录是否存在
if not os.path.exists(target_dir):
# 创建多级目录
os.makedirs(target_dir)
# 3, The files are backed up into a tar file
# 4, The name of subdirectory and tar file
today = time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the tar file
comment = raw_input('Enter a comment: ')
if len(comment) == 0:
target = target_dir + today + os.sep + now + '.tar.gz'
else:
target = target_dir + today + os.sep + comment.replace(' ','-') + '_' + now + '.tar.gz'
# Create the subdirectory if it isn't already there
if not os.path.exists(target_dir+today):
os.mkdir(target_dir+today)
print 'Successfully created directory',today
# 5, We use the tar command(in Unix/Linux) to put the files in a tgz archive
tar_command = "tar -zcf %s %s" % (target,' '.join(source))
# Run the backup
if os.system(tar_command) == 0:
print 'Successful backup to',target
else:
print 'Backup failed.'
# end

本文出自 “心静梵音” 博客,请务必保留此出处http://masters.blog.51cto.com/6516495/1553313
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: