Advertisement
Guest User

Untitled

a guest
Dec 20th, 2014
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. #! /usr/bin/env python2.7
  2. import os
  3. import sys
  4. import re
  5. import time
  6. import getopt
  7. import subprocess
  8. import logging
  9. import logging.handlers
  10.  
  11. directory   = '/tmp/binlogs/'
  12. verbose     = False
  13. compressed  = 0
  14. found       = 0
  15. total_time  = 0
  16.  
  17. # logging config
  18. log = logging.getLogger(__name__)
  19. log.setLevel(logging.DEBUG)
  20. handler = logging.handlers.SysLogHandler('/dev/log')
  21. formatter = logging.Formatter('%(module)s: %(message)s')
  22. handler.setFormatter(formatter)
  23. log.addHandler(handler)
  24.  
  25. # args parsing
  26. try:
  27.   opts, args = getopt.getopt(sys.argv[1:], 'd:vh', ['directory=', 'verbose', 'help'])
  28. except getopt.GetoptError:
  29.   print 'Invalid option. Use -h (--help) for help.'
  30.   log.error("==== The script has been called with illegal arguments")
  31.   sys.exit(2)
  32.  
  33. for opt, arg in opts:
  34.   if opt in ('-d', '--directory'):
  35.     directory = arg
  36.   elif opt in ('-v', '--verbose'):
  37.     verbose = True
  38.   elif opt in ('-h', '--help'):
  39.     print """
  40.      -v --verbose for verbose output
  41.      -d --directory for specific dir
  42.    """
  43.     sys.exit(0)
  44.  
  45. # start
  46. msg = "==== The script has started. Searching for matches in %s" % directory
  47. log.info(msg)
  48.  
  49. if verbose:
  50.   print msg
  51.  
  52. # file search + compress
  53. for file in os.listdir(directory):
  54.   if re.search('^mysql-bin\.\d{6}$', file):
  55.     found += 1
  56.     start = time.clock()
  57.     gzip_status = subprocess.call(["gzip", os.path.join(directory, file)])
  58.     total_time += time.clock() - start
  59.  
  60.     if gzip_status == 0:
  61.       log_message = "== [OK] %s compressed" % file
  62.       compressed += 1
  63.     else:
  64.       log_message = "== [--] %s found, but gzip exited with status %d" % (file, gzip_status)
  65.  
  66.     log.info(log_message)
  67.  
  68.     if verbose:
  69.       print log_message
  70.     else:
  71.       print "%s found" % file
  72.  
  73. if found > 0:
  74.   end_msg = "==== The script has ended without errors. Compressed %d of %d files succesfully in %.2f seconds"  % (found, compressed, total_time)
  75. else:
  76.   end_msg = "==== The script has ended without matching files"
  77. log.info(end_msg)
  78. if verbose:
  79.   print end_msg
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement