Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.14 KB | None | 0 0
  1. #!/usr/bin/python2.7
  2.  
  3. from collections import Counter
  4. from optparse import OptionParser
  5. from operator import itemgetter
  6. from re import search
  7. import datetime as dt
  8. import smtplib
  9. import os.path
  10. import gzip
  11.  
  12. whitelist = ['#######', '########']
  13. header = ''
  14. footer = ''
  15. diff = 0
  16. i=0
  17.  
  18. def intensity(time, count):
  19. global diff
  20. time = time.split('-')
  21. start = dt.datetime.strptime(time[1], '%H:%M')
  22. stop = dt.datetime.strptime(time[0], '%H:%M')
  23. diff = (start - stop).total_seconds()/3600
  24. return count/(200*(diff if diff > 0 else -diff+24))
  25.  
  26.  
  27. def inRange(start, end, x):
  28. return start <= x <= end if start <= end else start <= x or x <= end
  29.  
  30.  
  31. def tRange(file, time):
  32. if time == '0':
  33. for line in file:
  34. yield line
  35. else:
  36. try:
  37. time = time.split('-')
  38. time = [i.split(':') for i in time]
  39. start = dt.time(int(time[0][0]), int(time[0][1]), 0)
  40. stop = dt.time(int(time[1][0]), int(time[1][1]), 0)
  41. for line in file:
  42. x = line.split()[2].split(':')
  43. x = dt.time(int(x[0]), int(x[1]), int(x[2]))
  44. if inRange(start, stop, x):
  45. yield line
  46. except ValueError:
  47. print 'Can not set time from file, is it a maillog file?'
  48. exit()
  49. except IndexError:
  50. print 'Can not set time from -t parameter, is it valid?'
  51. exit()
  52.  
  53.  
  54. def hRange(file, time):
  55. global header, footer, i
  56. for i in tRange(file, time):
  57. if not header:
  58. header = i
  59. host = search('from=<(.*?)>', i)
  60. if host:
  61. host = host.group(1)
  62. if not host:
  63. continue
  64. host = host[host.find('@')+1:]
  65. yield host
  66. footer = i
  67.  
  68.  
  69. def scan(file, filename, path, time, limit, critical, quiet):
  70. global header, footer
  71. report, creport, count = [], [], 0
  72. hostrank = Counter(i for i in hRange(file, time))
  73. report = [i for i in hostrank.most_common() if i[1] > limit]
  74. if report:
  75. creport = [i for i in report if i[1] > critical and i[0] not in whitelist]
  76. cstate = ('reached, sending critical report to ###@###' if creport else 'not reached')
  77. count = sum(i[1] for i in hostrank.most_common())
  78. reportFile = path + '/maillog-audit-%s' % dt.datetime.now().strftime("%Y%m%d-%H:%M:%S")
  79. header = header.split()[:3]
  80. footer = footer.split()[:3]
  81. date = 'Date: from %s to %s' % (' '.join(header), ' '.join(footer))
  82. score = intensity(''.join([header[2][:-3], '-', footer[2][:-3]]), count)
  83. output = '''
  84. File: %s
  85. Settings: limit=%s, critical=%s, quiet=%s
  86. Report: done, %s
  87. Date/time range: %s
  88. Stats: messages=%s (%.2f per hour), intensity=%.2f%% (max 20000 msg per hour)
  89. Critical state: %s
  90. ''' % (filename, limit, critical, quiet, ('saved to %s' % reportFile), date, count, count/(diff if diff != 0 else 24),
  91. score, cstate)
  92. coutput = '''\tCritical hosts: (host msgs, host from whitelist excluded)\n%s\n''' % '\n'.join('\t{:30}\t{}'.format(*it) for it in [i for i in creport])
  93. print output
  94. if creport:
  95. print coutput
  96. print quiet
  97. if not quiet:
  98. From = '####@####'
  99. # To = '####@####'
  100. # smtp = smtplib.SMTP('localhost')
  101. # smtp.sendmail(From, To, 'Subject: Audit maillog_auditor.py\n'+output+coutput)
  102. output += 'Host:\t(host msgs)\n%s\n' % '\n'.join('\t{:30}\t{}'.format(*it) for it in [i for i in report])
  103. outfile = open(reportFile, 'w')
  104. outfile.write(output)
  105. outfile.close()
  106. else:
  107. print 'File:%s\nReport: done, nothing to report' % filename
  108.  
  109.  
  110. if __name__ == "__main__":
  111. parser = OptionParser()
  112. parser.add_option('-f', '--file', dest='filename', default='maillog', help='scan on FILE',
  113. metavar='FILE')
  114. parser.add_option('-l', '--limit', dest='limit', default=100,
  115. help='report (in file) hosts that have send more messages than LIMIT', metavar='LIMIT', type='int')
  116. parser.add_option('-c', '--critical', dest='critical', default=500,
  117. help='report (in: file, output, mail - optional) hosts that have send more messages than CRITICAL',
  118. metavar='CRITICAL', type='int')
  119. parser.add_option('-q', '--quiet', dest='quiet', default=False, help='don\'t send report to ####@####',
  120. action='store_true')
  121. parser.add_option('-t', '--time', dest='time', default='0',
  122. help='scan file in TIME range, syntax H:M-H:M', metavar='TIME')
  123. parser.add_option('-s', '--subst', dest='substracted', default=0,
  124. help='scan in time range: from s hours ago to now (scan last s hours of maillog)', metavar='SUBSTRACT')
  125. parser.add_option('-p', '--path', dest='path', help='set path for maillog-audit file', metavar=
  126. 'PATH')
  127.  
  128. (options, args) = parser.parse_args()
  129. options = vars(options)
  130. maillog = options['filename']
  131.  
  132. if options['substracted']:
  133. now = dt.datetime.now()
  134. options['time'] = (now - dt.timedelta(hours=int(options['substracted']))).strftime('%H:%M') + '-' + now.strftime('%H:%M')
  135.  
  136. if not os.path.exists(maillog):
  137. print 'File \"%s\" not found' % maillog
  138. exit()
  139.  
  140. path = dt.datetime.now().strftime("%Y%m%d")
  141. if options['path']:
  142. path = (options['path'] if options['path'][-1] == '/' else options['path'] + '/') + path
  143.  
  144. if not os.path.exists(path):
  145. os.makedirs(path)
  146.  
  147. print 'Scanning started...'
  148.  
  149. if maillog.endswith('.gz'):
  150. with gzip.open(maillog, 'r') as f:
  151. scan(f, maillog, path, options['time'], options['limit'], options['critical'], options['quiet'])
  152. else:
  153. with open(maillog, 'r') as f:
  154. scan(f, maillog, path, options['time'], options['limit'], options['critical'], options['quiet'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement