免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1825 | 回复: 1
打印 上一主题 下一主题

打算写一个备份的程序 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-05-17 00:27 |只看该作者 |倒序浏览
在网上找了一下,没有找到比较好的备份脚本,打算写一个备份的程序。




还没写完,等有时间再写,
请关注:http://netkiller.github.com/architect/solution/solution.backup.html
  1. #!/usr/bin/env python3
  2. #/bin/env python3
  3. #-*- coding: utf-8 -*-
  4. ##############################################
  5. # Home  : http://netkiller.sf.net
  6. # Author: Neo <openunix@163.com>
  7. ##############################################

  8. try:
  9.     import logging, configparser
  10.     import threading
  11.     from optparse import OptionParser, OptionGroup
  12.     import os,io,sys
  13. except ImportError as err:
  14.     print("Error: %s" %(err))

  15. class Runtime(threading.Thread):
  16.     def __init__(self, logging):
  17.         threading.Thread.__init__(self)
  18.         self.logging = logging
  19.         sys.stdin = open('stdin.log', 'r')
  20.         sys.stdout = open('stdout.log', 'w')
  21.         sys.stderr = open('stderr.log', 'w')
  22.     def command(self,cmd):
  23.         commands = {
  24.             'rsync': 'rsync -auzvP',
  25.             'sftp' : 'sftp',
  26.             'scp' : 'scp -r',
  27.             'cp' : 'cp -r'
  28.         }
  29.         return commands[cmd]
  30.     def policy(self,policy):
  31.         policies = {
  32.             'full': 'rsync -az',
  33.             'mirror': 'rsync -auz --delete',
  34.             'differential': 'rsync -auz --delete',
  35.             'incremental': 'rsync -auz',
  36.             'clone': 'dd',
  37.             'copy.cp': 'cp -au',
  38.             'copy.cp.backup': "cp  --suffix=$(date '+.%Y-%m-%d.%H:%M:%S') "
  39.             'copy.scp': 'scp -a',
  40.             'mirror.ftp': 'wget -m',
  41.             'mirror.http': 'wget -m',
  42.             'archive.zip': 'zip',
  43.             'archive.7zip': '7zip',
  44.             'archive.cpio': 'cpio',
  45.             'archive.tar': 'tar zcvf',
  46.             'snapshot': ''
  47.         }
  48.         return policies[policy]
  49.     def execute(self,cfg):
  50.         print( self.policy('mirror'))
  51.         #command = self.command(cfg['cmd'])
  52.         command = self.policy(cfg['policy']) + ' ' + cfg['source'] + ' ' + cfg['target'] + ' >> stdout.log'
  53.         self.logging.debug(command)
  54.         os.system(command)
  55. class Task():
  56.     def __init__(self, logging):
  57.         self.logging = logging
  58.         self.config = configparser.SafeConfigParser()
  59.         cfg='task.cfg'
  60.         self.config.read(cfg)
  61.     def list(self):
  62.         for section in self.config.sections():
  63.             print(section)
  64.     def new(self):
  65.         pass
  66.     def remove(self):
  67.         pass
  68.     def change(self):
  69.         pass
  70.     def run(self, section):
  71.         try:
  72.             #print(cfg)
  73.             cfg = self.config.items(section)
  74.             r = Runtime(self.logging)
  75.             r.execute(dict(cfg))
  76.         except configparser.NoSectionError as err:
  77.             print(err)
  78.     def show(self, section):
  79.         for item in self.config.items(section):
  80.             #k,v = item
  81.             print("%s: %s" %(item))
  82.     def get(self,section):
  83.         return self.config.items(section)
  84. class Schedule():
  85.     def __init__(self, logging):
  86.         self.logging = logging
  87.         self.config = configparser.SafeConfigParser()
  88.         cfg='schedule.cfg'
  89.         self.config.read(cfg)
  90.     def list(self):
  91.         for section in self.config.sections():
  92.             print(section)
  93.     def show(self, section):
  94.         for item in self.config.items(section):
  95.             print("%s: %s" %(item))
  96.     def new(self):
  97.         pass
  98.     def remove(self):
  99.         pass
  100.     def change(self):
  101.         system('backup.cron')
  102.     def status(self):
  103.         pass
  104.     def run(self, section):
  105.         threads = []
  106.         t = Task(self.logging)
  107.         #t.run(task)
  108.         for task,status in self.config.items(section):
  109.             if status :
  110.                 cfg = t.get(task)
  111.                 r  = Runtime(dict(cfg))
  112.                 r.setName('Thread-' + task)
  113.                 threads.append(r)
  114.         for t in threads:
  115.             #print(t.getName())
  116.             self.logging.info(t.getName())
  117.             t.start()
  118.             t.join()
  119. class Volume():
  120.     pass
  121. class Backup():
  122.     def __init__(self):
  123.         self.config = {}
  124.         #self.config['logfile'] = 'backup.log'

  125.         usage = "usage: %prog [options] arg1 arg2"
  126.         self.parser = OptionParser(usage)
  127.         self.parser.add_option("-f", "--file", dest="filename",
  128.                   help="write report to FILE", metavar="FILE")
  129.         self.parser.add_option("-q", "--quiet",
  130.                   action="store_false", dest="verbose", default=True,
  131.                   help="don't print status messages to stdout")
  132.         self.parser.add_option('','--config', dest="config", help='Read configuration options from file.', default='backup.cfg')

  133.         group = OptionGroup(self.parser, "arg1",
  134.                     "arg1: task | schedule")
  135.         self.parser.add_option_group(group)
  136.         group = OptionGroup(self.parser, 'arg2', 'arg2: list | new | remove | show')
  137.         self.parser.add_option_group(group)

  138.         self.parser.add_option('-v','--version',action='store_true', help='print version number')
  139.         self.parser.add_option('-d','--daemon', dest='daemon', action='store_true', help='run as daemon')
  140.         self.parser.add_option('','--logfile', help='logs file.', default='backup.log')

  141.         (options, args) = self.parser.parse_args()
  142.         self.configure(options)

  143.         try:
  144.             logging.basicConfig(level=logging.NOTSET,
  145.                     format='%(asctime)s %(levelname)-8s %(message)s',
  146.                     datefmt='%Y-%m-%d %H:%M:%S',
  147.                     filename=self.config['environment']['logfile'],
  148.                     filemode='a')
  149.             self.logging = logging.getLogger()
  150.         except AttributeError as err:
  151.             print("Error: %s %s" %(err, self.config['environment']['logfile']))
  152.             sys.exit(2)
  153.         pass

  154.     def configure(self,options):
  155.         if options.config:
  156.             cpr = configparser.SafeConfigParser()
  157.             cpr.read(options.config)
  158.             for sect in cpr.sections():
  159.                 self.config[sect] = dict(cpr.items(sect))
  160.                 #for (key,value) in cpr.items(sect):
  161.                 #    self.config[key] = value
  162.         #print(self.config)

  163.     def task(self, args):
  164.         try:
  165.             t = Task(self.logging)
  166.             if len(args) <= 1:
  167.                 t.list()
  168.             elif args[1] == 'list':
  169.                 t.list()
  170.             elif args[1] == 'run':
  171.                 if len(args) == 3:
  172.                     t.run(args[2])
  173.                 else:
  174.                     t.list()
  175.             elif args[1] == 'show':
  176.                 if len(args) == 3:
  177.                     t.show(args[2])
  178.                 else:
  179.                     t.list()
  180.             else:
  181.                 t.list()
  182.         except IOError as err:
  183.             print(err)
  184.         except configparser.NoSectionError as err:
  185.             t.list()
  186.             print(err)
  187.             self.logging.error(err)
  188.     def schedule(self,args):
  189.         try:
  190.             s = Schedule(self.logging)
  191.             if len(args) <= 1:
  192.                 s.list()
  193.             elif args[1] == 'list':
  194.                 s.list()
  195.             elif args[1] == 'show':
  196.                 if len(args) == 3:
  197.                     s.show(args[2])
  198.                 else:
  199.                     s.list()
  200.             elif args[1] == 'run':
  201.                 if len(args) == 3:
  202.                     s.run(args[2])
  203.                 else:
  204.                     s.list()
  205.             else:
  206.                 s.list()
  207.         except configparser.NoSectionError as err:
  208.             s.list()
  209.             self.logging.error(err)
  210.             print(err)
  211.     def usage(self):
  212.         self.parser.print_help()

  213.     def main(self):
  214.         (options, args) = self.parser.parse_args()
  215.         if options.daemon:
  216.             pid = os.fork()
  217.             if pid > 0:
  218.                 self.logging.info('daemon is ok')
  219.                 sys.exit(0)
  220.         if not args:
  221.             self.usage()
  222.         elif args[0] == 'task':
  223.             self.task(args)
  224.             self.logging.debug('Task')
  225.         elif args[0] == 'schedule':
  226.             self.schedule(args)
  227.             self.logging.debug('Schedule')
  228.         else:
  229.             print('')
  230. if __name__ == '__main__':
  231.     try:
  232.         backup = Backup()
  233.         backup.main()
  234.     except KeyboardInterrupt:
  235.         print ("Crtl+C Pressed. Shutting down.")
复制代码

论坛徽章:
381
CU十二周年纪念徽章
日期:2014-01-04 22:46:58CU大牛徽章
日期:2013-03-13 15:32:35CU大牛徽章
日期:2013-03-13 15:38:15CU大牛徽章
日期:2013-03-13 15:38:52CU大牛徽章
日期:2013-03-14 14:08:55CU大牛徽章
日期:2013-04-17 11:17:19CU大牛徽章
日期:2013-04-17 11:17:32CU大牛徽章
日期:2013-04-17 11:17:37CU大牛徽章
日期:2013-04-17 11:17:42CU大牛徽章
日期:2013-04-17 11:17:47CU大牛徽章
日期:2013-04-17 11:17:52CU大牛徽章
日期:2013-04-17 11:17:56
2 [报告]
发表于 2011-05-17 08:29 |只看该作者
mark,楼主写的不错,关注下.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP