Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python2.7
- from collections import Counter
- from optparse import OptionParser
- from operator import itemgetter
- from re import search
- import datetime as dt
- import smtplib
- import os.path
- import gzip
- whitelist = ['#######', '########']
- header = ''
- footer = ''
- diff = 0
- i=0
- def intensity(time, count):
- global diff
- time = time.split('-')
- start = dt.datetime.strptime(time[1], '%H:%M')
- stop = dt.datetime.strptime(time[0], '%H:%M')
- diff = (start - stop).total_seconds()/3600
- return count/(200*(diff if diff > 0 else -diff+24))
- def inRange(start, end, x):
- return start <= x <= end if start <= end else start <= x or x <= end
- def tRange(file, time):
- if time == '0':
- for line in file:
- yield line
- else:
- try:
- time = time.split('-')
- time = [i.split(':') for i in time]
- start = dt.time(int(time[0][0]), int(time[0][1]), 0)
- stop = dt.time(int(time[1][0]), int(time[1][1]), 0)
- for line in file:
- x = line.split()[2].split(':')
- x = dt.time(int(x[0]), int(x[1]), int(x[2]))
- if inRange(start, stop, x):
- yield line
- except ValueError:
- print 'Can not set time from file, is it a maillog file?'
- exit()
- except IndexError:
- print 'Can not set time from -t parameter, is it valid?'
- exit()
- def hRange(file, time):
- global header, footer, i
- for i in tRange(file, time):
- if not header:
- header = i
- host = search('from=<(.*?)>', i)
- if host:
- host = host.group(1)
- if not host:
- continue
- host = host[host.find('@')+1:]
- yield host
- footer = i
- def scan(file, filename, path, time, limit, critical, quiet):
- global header, footer
- report, creport, count = [], [], 0
- hostrank = Counter(i for i in hRange(file, time))
- report = [i for i in hostrank.most_common() if i[1] > limit]
- if report:
- creport = [i for i in report if i[1] > critical and i[0] not in whitelist]
- cstate = ('reached, sending critical report to ###@###' if creport else 'not reached')
- count = sum(i[1] for i in hostrank.most_common())
- reportFile = path + '/maillog-audit-%s' % dt.datetime.now().strftime("%Y%m%d-%H:%M:%S")
- header = header.split()[:3]
- footer = footer.split()[:3]
- date = 'Date: from %s to %s' % (' '.join(header), ' '.join(footer))
- score = intensity(''.join([header[2][:-3], '-', footer[2][:-3]]), count)
- output = '''
- File: %s
- Settings: limit=%s, critical=%s, quiet=%s
- Report: done, %s
- Date/time range: %s
- Stats: messages=%s (%.2f per hour), intensity=%.2f%% (max 20000 msg per hour)
- Critical state: %s
- ''' % (filename, limit, critical, quiet, ('saved to %s' % reportFile), date, count, count/(diff if diff != 0 else 24),
- score, cstate)
- 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])
- print output
- if creport:
- print coutput
- print quiet
- if not quiet:
- From = '####@####'
- # To = '####@####'
- # smtp = smtplib.SMTP('localhost')
- # smtp.sendmail(From, To, 'Subject: Audit maillog_auditor.py\n'+output+coutput)
- output += 'Host:\t(host msgs)\n%s\n' % '\n'.join('\t{:30}\t{}'.format(*it) for it in [i for i in report])
- outfile = open(reportFile, 'w')
- outfile.write(output)
- outfile.close()
- else:
- print 'File:%s\nReport: done, nothing to report' % filename
- if __name__ == "__main__":
- parser = OptionParser()
- parser.add_option('-f', '--file', dest='filename', default='maillog', help='scan on FILE',
- metavar='FILE')
- parser.add_option('-l', '--limit', dest='limit', default=100,
- help='report (in file) hosts that have send more messages than LIMIT', metavar='LIMIT', type='int')
- parser.add_option('-c', '--critical', dest='critical', default=500,
- help='report (in: file, output, mail - optional) hosts that have send more messages than CRITICAL',
- metavar='CRITICAL', type='int')
- parser.add_option('-q', '--quiet', dest='quiet', default=False, help='don\'t send report to ####@####',
- action='store_true')
- parser.add_option('-t', '--time', dest='time', default='0',
- help='scan file in TIME range, syntax H:M-H:M', metavar='TIME')
- parser.add_option('-s', '--subst', dest='substracted', default=0,
- help='scan in time range: from s hours ago to now (scan last s hours of maillog)', metavar='SUBSTRACT')
- parser.add_option('-p', '--path', dest='path', help='set path for maillog-audit file', metavar=
- 'PATH')
- (options, args) = parser.parse_args()
- options = vars(options)
- maillog = options['filename']
- if options['substracted']:
- now = dt.datetime.now()
- options['time'] = (now - dt.timedelta(hours=int(options['substracted']))).strftime('%H:%M') + '-' + now.strftime('%H:%M')
- if not os.path.exists(maillog):
- print 'File \"%s\" not found' % maillog
- exit()
- path = dt.datetime.now().strftime("%Y%m%d")
- if options['path']:
- path = (options['path'] if options['path'][-1] == '/' else options['path'] + '/') + path
- if not os.path.exists(path):
- os.makedirs(path)
- print 'Scanning started...'
- if maillog.endswith('.gz'):
- with gzip.open(maillog, 'r') as f:
- scan(f, maillog, path, options['time'], options['limit'], options['critical'], options['quiet'])
- else:
- with open(maillog, 'r') as f:
- scan(f, maillog, path, options['time'], options['limit'], options['critical'], options['quiet'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement