Python 备份脚本

#!/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


你可能感兴趣的:(python,备份脚本)