python备份目录脚本

2023-01-31 01:01:39 备份 目录 脚本

此脚本适用于备份指定发布目录下的目录,可适当修改运用!


#!/usr/bin/env python
#backup app Python script.
import os
import time
import sys

nowTime = time.strftime("%Y%m%d")

sourcePath = '/home/zcb/resin-4.0.10/apps/'
backupPath = '/home/zcb/tmp/bak'+nowTime

if not os.path.exists('/home/zcb/tmp/bak'+nowTime):
 os.mkdir('/home/zcb/tmp/bak'+nowTime)
 print time.strftime("%Y-%m-%d")+' Backup Directory create successfully!'


applist = []
def getAppList():
 all = os.listdir(sourcePath)
 for i in all:
  if os.path.isdir(sourcePath+i):
   applist.append(i)

def backup_all():
 print  "%s  App Backuping...." % time.strftime("%Y-%m-%d")
 print "-" * 35
 for appName in applist:
  os.chdir(sourcePath)
  tar_command = 'tar -zcf %s/%s.tar.gz %s' % (backupPath,appName,appName)
  if os.system(tar_command) == 0:
          print "\033[;32m%s backup successfully!\033[0m" % appName
         else:
          print "\033[;31m%s backup failed!\033[0m" % appName
 print "-" * 35
 print "End"

def backup_single():
 print  "%s  App Backuping...." % time.strftime("%Y-%m-%d")
        print "-" * 35
        os.chdir(sourcePath)
        tar_command = 'tar -zcf %s/%s.tar.gz %s' % (backupPath,appName,appName)
        if os.system(tar_command) == 0:
         print "\033[;32m%s backup successfully!\033[0m" % appName
        else:
         print "\033[;31m%s backup failed!\033[0m" % appName
        print "-" * 35
        print "End"

if len(sys.argv) == 2:
 appName = sys.argv[1]
 getAppList()
 if appName in applist:
  backup_single()
 else:
  print "%s not exist, Please try again!" % appName
else:
 input = raw_input("No input any parameters, whether to perfORM a full backup?(y/n) ")
 if input == 'y' or input == 'Y':
  getAppList()
  backup_all()
 else:
  print "Exit Backup, Bye!~"
#print applist


相关文章