backup.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python
  3. """
  4. TODO 利用parse 和 string formatting 以及 读取配置文件json 或者环境变量
  5. """
  6. import subprocess
  7. import click
  8. import delegator
  9. @click.group
  10. def cli():
  11. pass
  12. class Command(object):
  13. def __init__(self, executor):
  14. self._executor = executor
  15. def build(self, **options):
  16. prefix = lambda _ : '-' if len(_) == 1 else '--'
  17. return [self._executor] + [ prefix(k) + ' '.join((k, v)) for k, v in options]
  18. def run(self, **options):
  19. actions = self.build(**options)
  20. return subprocess.check_output(actions).decode('utf-8')
  21. class ShellCommand(Command):
  22. def __init__(self, template):
  23. self.template = template
  24. def run(self, **options):
  25. return delegator.run(self.template.format_map(options))
  26. mongodump = ShellCommand('mongodump -u {user} -p {password} --authenticationDatabase {authdb} --host {host} --port {port} -d {destDB} -o {destDir}')
  27. mongorestore = ShellCommand('mongorestore -u {user} -p {password} --authenticationDatabase {authdb} --host {host} --port {port} -d {destDB} --dir {destDir}')
  28. @cli.command()
  29. @click.option('-f','--filepath', prompt=u'请输入要转换的表格文件路径')
  30. @click.option('-s','--sync', prompt=u'同步')
  31. @click.option('-c','--config', prompt=u'配置')
  32. def mongo():
  33. restore = Command(executor='mongorestore')
  34. dump = Command(executor='mongodump')
  35. ### Memcached
  36. def backup_memcached(host, port, toFileName):
  37. """
  38. memcached-tool 127.0.0.1:11211 dump > 11211data
  39. memcached-tool 127.0.0.1:11212 dump > 11212data
  40. """
  41. delegator.run('memcached-tool {host}:{port} dump > {toFileName}'\
  42. .format(host=host, port=port, toFileName=toFileName))
  43. def restore_memcached(host, port, fromFileName):
  44. """
  45. nc localhost 11211 < 11211data
  46. nc localhost 11212 < 11212data
  47. """
  48. delegator.run('nc {host} {port} < {fromFileName}'.format(host=host, port=port, fromFileName=fromFileName))