forked from tahz7/traffic_analyser
/
traffic_analyser.py
1885 lines (1638 loc) · 77.8 KB
/
traffic_analyser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author: Tahzeem Taj
# tahzeem.taj@gmail.com
# Source: https://github.com/tahz7/traffic_analyser
from datetime import datetime, timedelta
import json
import urllib2
import socket
import sys
import re
import time
import os
import gzip
from sys import stdout
from time import sleep
from optparse import OptionParser
from collections import defaultdict
from operator import itemgetter
class Col(object):
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
PURPLE = '\033[35m'
LIGHTRED = '\033[91m'
CYAN = '\033[36m'
U = '\033[4m'
ENDC = '\033[0m'
class Title(object):
line = u'●▬▬▬▬▬▬▬▬▬▬▬▬▬▬๑۩۩๑▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬●'
traffic_analyser = u'▂▃▅▇█▓▒░۩۞۩ TRAFFIC ANALYSER ۩۞۩░▒▓█▇▅▃▂'
log_info = u'▂▃▅▇█▓▒░۩۞۩ LOGS INFO ۩۞۩░▒▓█▇▅▃▂'
log_result = u'▂▃▅▇█▓▒░۩۞۩ LOG RESULTS ۩۞۩░▒▓█▇▅▃▂'
general_info = u'▂▃▅▇█▓▒░۩۞۩ GENERAL INFO ۩۞۩░▒▓█▇▅▃▂'
class CmdArgs(object):
def __init__(self):
self.cmd_args = defaultdict(dict)
def args_validation(self, options, args, parser, help_text):
"""
Validate command line options/arguments
"""
if options.help:
print help_text
sys.exit()
# set default options
if len(sys.argv) < 2:
options.compact = (10, 10)
options.hour = 1
self.cmd_args['default_arg'] = "--compact 10 10 --hour 1"
elif (options.select or options.log) and not (options.compact or
options.ip or
options.rmatch or
options.ipmatch or
options.request or
options.hour or
options.min or
options.day or
options.date):
options.compact = (10, 10)
options.hour = 1
self.cmd_args['default_arg'] = "--compact 10 10 --hour 1"
elif (options.select or options.log) and (options.hour or
options.min or
options.date or
options.day) and not (
options.compact or options.ip or
options.rmatch or options.ipmatch or
options.request):
options.compact = (10, 10)
self.cmd_args['default_arg'] = "--compact 10 10"
elif (options.select or options.log) and (options.compact or
options.ip or
options.rmatch or
options.ipmatch or
options.request) and not (
options.hour or
options.min or
options.date or
options.day):
options.hour = 1
self.cmd_args['default_arg'] = "--hour 1"
elif (options.compact or options.ip or options.rmatch or
options.ipmatch or options.request) and not (options.hour or
options.min or
options.date or
options.day):
options.hour = 1
self.cmd_args['default_arg'] = "--hour 1"
elif (options.hour or options.min or options.date or
options.day) and not (options.compact or options.ip or
options.rmatch or options.ipmatch or
options.request):
options.compact = (10, 10)
self.cmd_args['default_arg'] = "--compact 10 10"
if options.log:
# cycle will display results for each individual log file
if 'cycle' in options.log:
self.cmd_args['cycle_all'] = True
options.log.remove('cycle')
# remove duplicate values in options.log and args (this occurs when
# options.log and (options.rmatch or options.ipmatch)) is input
for log_file in options.log:
# cycle will display results for each individual log file
if log_file in args:
args.remove(log_file)
elif not os.path.exists(log_file):
parser.error("Could not find this log file; {0}. Make sure"
" you've got the correct file name".format(
log_file))
elif options.dir:
sys.exit("--dir options has been removed. Use {0} instead.".format(
Col.CYAN + "--log /path/to/directory/*" + Col.ENDC))
if options.date:
args_number = len(options.date)
if args_number > 2:
parser.error(
'You input more than two arguments. '
'The correct formatting should be: date/month/year:hour:'
'minute:second | 10/Jan/2017:15:00:00')
if args_number == 2:
try:
datetime.strptime(options.date[0], "%d/%b/%Y:%H:%M:%S")
datetime.strptime(options.date[1], "%d/%b/%Y:%H:%M:%S")
except ValueError:
parser.error('Either from_time or to_time is incorrectly '
'formatted. The correct formatting should '
'be: date/month/year:hour:minute:second | '
'10/Jan/2017')
else:
regex_date = re.search(r"(\d{2}/\w+/\d{4})", options.date[0])
if regex_date:
try:
datetime.strptime(options.date[0], "%d/%b/%Y")
self.cmd_args['single_date'] = True
except ValueError:
parser.error(
'There was a problem with your --date argument. '
'The correct formatting should be: date/month/year'
' | 10/Aug/2016:15:00:00')
else:
parser.error(
'There was a problem with your --date argument. '
'The correct formatting should be: date/month/year'
' | 10/Aug/2016:15:00:00')
if options.ipmatch:
try:
options.ipmatch[0] = int(options.ipmatch[0])
except ValueError:
parser.error(
'The first argument for option -ipmatch is request_number '
'which needs to be an integer')
if len(args) < 1:
parser.error(
'The second argument (and so forth) for option -ipmatch '
'needs to be a ip')
if options.rmatch:
try:
options.rmatch[0] = int(options.rmatch[0])
except ValueError:
parser.error(
'The first argument for option --rmatch is ip_number '
'which needs to be an integer')
if len(args) < 1:
parser.error(
'The second argument (and so forth) for option --rmatch '
'needs to be a request string')
if options.filter:
options.filter = options.filter.upper()
if options.filter not in ['POST', 'GET']:
parser.error(
'The --filter option takes only one of these two '
'arguments; POST or GET')
if options.select:
for item in args:
if item.lower() == 'all':
args.remove(item)
self.cmd_args['cycle_all'] = True
if options.ten:
if options.ten.lower() not in ['on', 'off']:
parser.error("You can only use the --ten option with either "
"on or off argument. ie. --ten on (to enable ten "
"minute intervals)")
elif options.ten.lower() == 'on':
self.cmd_args['ten_min'] = True
else:
self.cmd_args['ten_min'] = False
# Ensure only one option per option group is selected
time_list = []
data_list = []
log_list = []
search_list = []
for option, arg in vars(options).iteritems():
if arg not in [None, False]:
if option in ['day', 'hour', 'min', 'date']:
time_list.append(option)
if option in ['ip', 'request', 'ipmatch', 'rmatch', 'compact']:
data_list.append(option)
if option in ['select', 'log', 'dir']:
log_list.append(option)
if option in ['complete', 'top']:
search_list.append(option)
for item in [time_list, data_list, log_list, search_list]:
if len(item) > 1:
parser.error('You can only use one of the following '
'options: ' + ' '.join(['--{0}'.format(option)
for option in item]))
# Ensure both time and data options are input as a minimum
# for the script to work.
if not time_list or not data_list:
parser.error('You must choose at least one time group option '
'(--min, --hour, --day, --date) and one data group '
'option (--ip, --request, --ipmatch, --rmatch, '
'--compact)')
return options, args
def multi_args(self, option, opt_str, value, parser):
""" Normally you can append variable arguments into the args list
but this can lead to data clashes if --rmatch or --ipmatch is also
used. For avoidance this function is currently used to append
arguments for the --log option.
"""
args = []
for arg in parser.rargs:
if arg[0] != "-":
args.append(arg)
else:
del parser.rargs[:len(args)]
break
if getattr(parser.values, option.dest):
args.extend(getattr(parser.values, option.dest))
setattr(parser.values, option.dest, args)
def main_args(self):
# format options when displayed
lst_args = ['Time Options', 'minute', 'hour', 'day', 'from time',
'to time', 'day', 'Data Options', 'ip number',
'request number', 'ip number', 'request number',
'request number', 'ip number', 'request number',
'list of ip\'s', 'ip number', 'list of requests',
'Log Options', 'all', 'log file(s)', 'log file(s)',
'Search Options', 'Miscellaneous Options', 'on/off',
'get/post']
lst_args_format = map(lambda x: Col.U + x + Col.ENDC
if x not in ['Time Options', 'Data Options',
'Log Options', 'Search Options',
'Miscellaneous Options'] else
Col.LIGHTRED + x + Col.ENDC, lst_args)
help_text = '''\n Options:
-h, --help show this help message and exit
{0}
--min {1} Get data from last X minutes
--hour {2} Get data from last X hour(s)
--day {3} Get data from last X day(s)
--date {4} {5} or --date {6}
Get data from between two dates (Example;
date/month/year:hour:minute:second |
10/Aug/2016:15:00:00). Or get the whole day
(Example: 11/Jan/2017)
{7}
--compact {8} {9}
Get a simple version of a list of the top X
ip's and a list of the top X requests.
(Example: --compact 10 10)
--ip {10} {11}
Get the top X ip's along with their top X
requests
--request {12} {13}
Get the top X requests's along with their top
X ip's
--ipmatch {14} {15}
Get top X requests for user input list of
ip'(s)s. (Example: --ipmatch 20 10.10.23.42
134.134.3.13)
--rmatch {16} {17}
Get top X ip's for user input list of
request(s).
(Example: --rmatch 10 xmlrpc.php wp-login.php)
{18}
--select or --select {19}
Choose which logs to check from a list of logs
currently opened by nginx/apache. Or you can
cycle all the open log files using
--select all
--log {20} or --log cycle {21}
Choose which log files to read from (you can
input multiple log files, (Example; --log
google_access_log /var/log/httpd/*access*) Or
you can cycle the log files to get data
per-log file
(Example: --log cycle logfile1 logfile2)
{22}
By default logs are read from bottom to top. You can
override this setting using the following;
--top
Read log files from the top down (by
default logs are read from the bottom line
up)
--complete
Read every line in log files from the top
to bottom line
{23}
--nogeo Disable geo information per ip
--ten {24}
Manually enable or disable10 min hit count
intervals. By default the 10 minute interval
hit count is disabled for data over 6 hours.
--filter {25}
filter requests by POST or GET
Further documentation can be viewed in the Wiki -
https://github.com/tahz7/traffic_analyser/wiki
'''.format(*lst_args_format)
parser = OptionParser(
usage=help_text, conflict_handler="resolve", add_help_option=False)
# time options group
parser.add_option('-m', '--min', type='int', nargs=1)
parser.add_option('-k', '--hour', type='int', nargs=1)
parser.add_option('-d', '--day', type='int', nargs=1)
parser.add_option('-d', '--date', action="callback",
callback=self.multi_args, dest="date")
# data options group
parser.add_option('-c', '--compact', type='int', nargs=2)
parser.add_option('-i', '--ip', type='int', nargs=2)
parser.add_option('-r', '--request', type='int', nargs=2)
parser.add_option('-i', '--ipmatch', action='append')
parser.add_option('-r', '--rmatch', action='append')
# log options group
parser.add_option('-s', '--select', action='store_true')
parser.add_option("-l", "--log", action="callback",
callback=self.multi_args, dest="log")
parser.add_option('-d', '--dir', nargs=1)
# search options group (method of searching through a log file)
parser.add_option('-t', '--top', action='store_true')
parser.add_option('-c', '--complete', action='store_true')
# miscellaneous options group
parser.add_option('-t', '--ten', type='str', nargs=1)
parser.add_option(
'-g', '--nogeo', help='Disable geo information per ip',
action='store_true')
parser.add_option(
'-f', '--filter', help='filter requests by POST or GET',
type='str',
nargs=1)
parser.add_option('-h', '--help', dest='help', action='store_true',
help='show this help message and exit')
# args is used for variable user inputs for rmatch and ipmatch only.
# Options for other user input
(options, args) = parser.parse_args()
options, args = self.args_validation(options, args, parser, help_text)
self.cmd_args['opts'] = options
self.cmd_args['args'] = args
self.cmd_args['help_text'] = help_text
return self.cmd_args
class GetData(object):
def __init__(self, cmd_args):
self.cmd_args = cmd_args
# contains httpd type, log files, time period
self.data = defaultdict(dict)
def control_flow(self):
opts = self.cmd_args['opts']
# get start and end times
start_time, end_time = self.start_end_dates(opts)
# check whether to enable/disable ten min interval
self.ten_min_interval(start_time, end_time)
# get httpd type and httpd pids
httpd_pid_dict = self.get_httpd_type(opts)
# get log files
self.get_log_files(opts,
httpd_pid_dict)
# get ip and request number
self.ip_req_number_args(opts)
return self.data
def total_seconds(self, time_input):
return ((time_input.microseconds + 0.0 +
(time_input.seconds + time_input.days * 24 * 3600) *
10 ** 6) / 10 ** 6)
def ten_min_interval(self, start_time, end_time):
""" Disable ten min interval hit count if date range is over 6 hours.
Otherwise disable/enable based on --ten option
"""
if (self.total_seconds(end_time - start_time) / 3600 < 6 and (
'ten_min' not in self.cmd_args) or
self.cmd_args['ten_min']):
self.data['ten_min_enable'] = True
def get_log_files(self, opts, httpd_pid_dict):
""" Grab log files based on options/args """
logs = set()
# add logs input by user
if opts.log:
for log_file in opts.log:
if os.path.isfile(log_file):
logs.add(log_file)
# Otherwise, get the log files that are currently open by either
# Apache/Ngninx.
else:
httpd_pid = httpd_pid_dict[self.data['httpd_type']]['ports']
for pid in httpd_pid:
try:
for log_file in os.listdir('/proc/{0}/fd'.format(pid)):
log_file = os.readlink(
"/proc/{0}/fd/{1}".format(pid, log_file))
# Don't include deleted files
if 'access' in log_file and ('(deleted)' not in
log_file):
logs.add(log_file)
except IOError:
continue
start_time, end_time = (self.data['time_period'][0],
self.data['time_period'][1])
# total_logs = len(logs)
# get log file size + date and then add to data dict
for log_file in logs:
log_size = self.filesize(os.path.getsize(log_file))
log_last_modified = datetime.strptime(
time.ctime(os.path.getmtime(log_file)), '%a %b %d %H:%M:%S %Y')
if start_time <= log_last_modified and (log_size != '0.00 B'):
self.data['logs'][log_file] = log_size
self.data['last_modified'][log_file] = log_last_modified
# add total log files count
self.data['log_count'] = len(self.data['logs'])
self.data['logs_skipped'] = len(logs) - len(self.data['logs'])
if self.data['log_count'] == 0:
print ("There are no log files to check. Exiting script..."
"\n\n Note: if a log file is empty or its 'last modified "
"time' is not within the time-range specified, then the "
"script will skip it.")
sys.exit()
# List logs opened by apache/nginx and let the user choose
if opts.select and 'cycle_all' not in self.cmd_args:
print
# prompt user to choose log files to check
for n, (log_file, size) in enumerate(
self.data['logs'].iteritems(), 1):
print '{0}. {1} [{2}]'.format(n,
Col.YELLOW + log_file +
Col.ENDC, size)
print
log_count = len(self.data['logs'])
while True:
try:
sys.stdin = open('/dev/tty')
user_input = raw_input(
"Which logs would you like to analyse? "
"(eg. 1 3 4 or all) ")
input_list = user_input.split()
if not input_list:
print (
"You need to make sure your input is either"
" all(selects all logs) or are digits with "
"spacing between them (ie. 4 3 2 1)")
else:
if 'all'.lower() in input_list:
break
else:
input_list = [int(a) for a in input_list]
# Check user input is correct
if (max(input_list) >
log_count or min(input_list) <
1):
print ("Error: The logs range from 1 to "
"{0}, so where did you get {1} "
"from...?".format(log_count,
max(input_list)))
else:
# remove logs the user doesn't want
for n, log_file in enumerate(
self.data['logs'].copy().keys(), 1):
if n not in input_list:
self.data['logs'].pop(log_file)
self.data['last_modified'].pop(
log_file)
self.data['log_count'] = len(self.data['logs'])
break
except ValueError:
print ("You need to make sure your input is either"
" all(selects all logs) or are digits with "
"spacing between them (ie. 4 3 2 1)")
return self.data
def filesize(self, bytes, suffix='B'):
""" Convert bytes to readable format. """
for unit in ['', 'K', 'M', 'G', 'T']:
if abs(bytes) < 1024.0:
return "{0:.2f} {1}{2}".format(round(bytes, 2), unit, suffix)
bytes /= 1024.0
def get_httpd_type(self, opts):
""" Get httpd version (nginx or apache) """
httpd_pid_dict = defaultdict(dict)
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
for pid in pids:
try:
if os.path.exists('/proc/{0}/exe'.format(pid)):
processes = os.readlink('/proc/{0}/exe'.format(pid))
regex_process = re.search("(httpd|nginx|apache2)+",
processes)
if regex_process is not None:
httpd_regex = regex_process.group(1)
if httpd_regex in ['apache2', 'httpd']:
httpd_regex = 'apache'
(httpd_pid_dict[httpd_regex].
setdefault('ports', []).append(pid))
except IOError:
continue
if not httpd_pid_dict and not opts.log:
sys.exit("{0}\nERROR: The script cannot continue as it could not"
" detect nginx or apache running. Also the '--log' option"
" is not used.".format(self.cmd_args['help_text']))
elif not httpd_pid_dict and opts.log:
httpd_type = "Webserver not detected."
self.data['httpd_extra_info'] = "--log option is used"
elif len(httpd_pid_dict) > 1:
# if both nginx/apache running, grab what's listening on port 80
httpd_type = self.httpd_port_number(httpd_pid_dict)
self.data['httpd_extra_info'] = ("Both nginx/apache detected, "
"defaulting to what's "
"listening on port 80")
else:
httpd_type = list(httpd_pid_dict)[0]
self.data['httpd_type'] = httpd_type
return httpd_pid_dict
def socket_number(self, socket_no=None):
""" Get one of the socket number(s) listening on tcp/tcp6 port 80
"""
for protocol in ['tcp', 'tcp6']:
with open(os.path.join('/proc/net', protocol), 'r') as socket_file:
socket_table = socket_file.readlines()
for line in socket_table:
line = line.split()
if line[3] == '0A':
hex_port = line[1].split(':')[1]
port = int(hex_port, 16)
if port == 80:
socket_no = line[-8]
break
return socket_no
def httpd_port_number(self, httpd_list):
""" Find whether apache or nginx is listening on port 80
"""
socket_no = self.socket_number()
httpd_type = None
if socket_no:
for httpd, port in httpd_list.iteritems():
pid = port['ports'][0]
try:
for filename in os.listdir('/proc/{0}/fd'.format(pid)):
filename = os.readlink(
"/proc/{0}/fd/{1}".format(pid, filename))
# check if socket number matches open sockets for
# httpd pid
if socket_no in filename:
# print filename
httpd_type = httpd
break
except IOError:
continue
# Quit if cannot detect what is running on port 80
if not httpd_type:
print ("{0}\nERROR: Could not detect whether apache or nginx is "
"listening on port 80".format(self.cmd_args['help_text']))
sys.exit()
return httpd_type
def calculate_start_time(self, metric, args_time):
"""
calculate the start time variable for min, hour and day.
"""
start_time = ((datetime.now() -
timedelta(**{metric: args_time})).
strftime("%d/%b/%Y:%H:%M:%S"))
return start_time
def start_end_dates(self, opts):
"""
Get the start/end dates based on user input
"""
# end time is current time unless --date option is used.
end_time = datetime.now().strftime("%d/%b/%Y:%H:%M:%S")
if opts.day:
args_time = opts.day
start_time = self.calculate_start_time('days', args_time)
elif opts.min:
args_time = opts.min
start_time = self.calculate_start_time('minutes', args_time)
elif opts.hour:
args_time = opts.hour
start_time = self.calculate_start_time('hours', args_time)
elif 'single_date' in self.cmd_args: # --date option:
args_date = datetime.strptime(opts.date[0], "%d/%b/%Y")
start_time = datetime.strftime(args_date, "%d/%b/%Y:%H:%M:%S")
if datetime.now().date() != args_date.date():
end_time = opts.date[0] + ":23:59:59"
else:
start_time = opts.date[0]
end_time = opts.date[1]
start_time = datetime.strptime(start_time,
"%d/%b/%Y:%H:%M:%S")
end_time = datetime.strptime(end_time, "%d/%b/%Y:%H:%M:%S")
self.data.setdefault('time_period', []).extend(
[start_time, end_time])
return start_time, end_time
def ip_req_number_args(self, opts):
""" assigns user options to ip number and request number. """
if opts.ip:
ip_no = opts.ip[0]
request_no = opts.ip[1]
elif opts.request:
ip_no = opts.request[1]
request_no = opts.request[0]
elif opts.rmatch:
request_no = None
ip_no = int(opts.rmatch[0])
elif opts.ipmatch:
ip_no = None
request_no = opts.ipmatch[0]
else: # options.compact
ip_no = opts.compact[0]
request_no = opts.compact[1]
# Limit geo api to 30 ip's to avoid potential abuse.
if not opts.nogeo:
if ip_no > 30:
self.data['geo_limit'] = ip_no
ip_no = 30
self.data['ip_no'] = ip_no
self.data['request_no'] = request_no
class LogDataStructure(object):
def ip_record(self):
""" Count hits per ip and hits for requests per ip.
Used with the --ip/--ipmatch option.
"""
return {
'count': 0,
'get_post': Counter(),
'date': defaultdict(self.date_record)
}
def request_record(self):
""" Count hits per requests and hits for ip per requests.
Used with the --request/--rmatch option.
"""
return {
'count': 0,
'ip': Counter(),
'date': defaultdict(self.date_record)
}
def compact_record(self):
""" Count top ip and top requests only. Used with --compact option """
return {
'ip': Counter(),
'request': Counter()
}
def date_record(self):
""" Count hits per date and per hour for either ip or request only.
Used with --ip/--request option.
"""
return {
'count': 0,
'hour': defaultdict(self.ten_minutes_record),
}
def ten_minutes_record(self):
""" Count hits per every 10 minutes """
return {
'count': 0,
'ten_min': Counter()
}
# This default dict gets combined hits of all data
def overall_date_count(self):
""" Count all hits per date and per hour """
return {
'count': 0,
'hour': defaultdict(self.ten_minutes_record),
}
class AnalyseLogs(LogDataStructure):
def __init__(self, cmd_args, data):
super(LogDataStructure, self).__init__()
self.cmd_args = cmd_args
self.data = data
self.hit_count = 0
# If the start/end time is longer than 6 hours, then we want
# disable the 10 min intervals for readability
self.ten_min_enable = (True if 'ten_min_enable' in self.data else
False)
if self.cmd_args['opts'].ipmatch or (
self.cmd_args['opts'].rmatch):
self.date_count = None
else:
# overall date count dict
self.date_count = defaultdict(self.overall_date_count)
# Use the relevant count dict for requests or ip
if self.cmd_args['opts'].request or self.cmd_args['opts'].rmatch:
self.ip_req_count = defaultdict(self.request_record)
elif self.cmd_args['opts'].ip or self.cmd_args['opts'].ipmatch:
self.ip_req_count = defaultdict(self.ip_record)
else: # create a new dict for compact option
self.ip_req_count = self.compact_record()
# month dict for converting time into datetime object
self.month_dict = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5,
'Jun': 6, 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10,
'Nov': 11, 'Dec': 12}
def grab_log_data(self):
""" Get data from logs """
ip_req_count, date_count = self.get_data_from_logs()
logs_data = ip_req_count, date_count
return logs_data
def regex_compile(self, opts):
""" Compile regex's for matching log file lines """
# compile date and request regex
regex_date_compile = r"(\d{2}/\w+/\d{4}:\d{2}:\d{2}:\d{2})"
regex_date = re.compile(regex_date_compile).search
if opts.filter:
# Only look for requests that start with get or post
regex_requests_compile = r'"%s[^"]*" \d{3}' % opts.filter
else: # get all request matches
regex_requests_compile = r'"[^"]*" \d{3}'
regex_requests = re.compile(regex_requests_compile).search
return regex_date, regex_requests
# This func adds ip/requests/time data to count dictionaries
def dict_add(self, req_ip, found_time_date, found_time_hour,
found_time_minute):
""" add date data to ip or request dict """
# regex_req_ip can be ip or request
self.ip_req_count[req_ip]['count'] += 1
# add date
self.ip_req_count[req_ip]['date'][found_time_date]['count'] += 1
# add hour
self.ip_req_count[req_ip]['date'][found_time_date][
'hour'][found_time_hour]['count'] += 1
if self.ten_min_enable:
# add 10 minute interval
self.ip_req_count[req_ip]['date'][found_time_date]['hour'][
found_time_hour]['ten_min'][
found_time_minute[0]] += 1
def dict_date_add(self, found_time_date, found_time_hour,
found_time_minute):
""" Add date data to overall date count dict """
# add date
self.date_count[found_time_date]['count'] += 1
# add hour
self.date_count[found_time_date]['hour'][found_time_hour]['count'] += 1
# add 10 minute interval
self.date_count[found_time_date]['hour'][found_time_hour][
'ten_min'][found_time_minute[0]] += 1
def evaluate_line(self, line, start_time, end_time,
regex_date, regex_requests, opts, args, found_time=None):
""" Grab required data from log line """
regex_date = regex_date(line)
regex_requests = regex_requests(line)
if regex_date and regex_requests:
date = regex_date.group()
# convert line date into datetime object
yr = int(date[7:11])
mon = self.month_dict[(date[3:6])]
day = int(date[0:2])
hr = date[12:14]
minute = date[15:17]
sec = int(date[18:20])
found_time = datetime(yr, mon, day, int(hr), int(minute), sec)
found_time_date = found_time.date()
found_time_hour = date[12:14]
found_time_minute = date[15:17]
# compare time from log line to user input time range
if start_time <= found_time <= end_time:
requests = regex_requests.group()
ip = line.split()[0]
if opts.request or opts.rmatch:
# collect data based upon requests
req_ip = requests
else: # instead do it for ip
req_ip = ip
# add to overall dict count
if not opts.rmatch and not opts.ipmatch:
self.dict_date_add(found_time_date, found_time_hour,
found_time_minute)
if opts.ipmatch:
# compare ip with the ip's from user input
ipmatch_list = args
if req_ip in ipmatch_list:
self.dict_add(req_ip, found_time_date,
found_time_hour, found_time_minute)
self.ip_req_count[req_ip]['get_post'][
requests] += 1
elif opts.rmatch:
# compare request with the requests from user input
rmatch_list = args
if any(x in requests for x in rmatch_list):
self.dict_add(req_ip, found_time_date,
found_time_hour, found_time_minute)
self.ip_req_count[req_ip]['ip'][ip] += 1
# compact option collects only ip's and requests without
# their time hit count data
elif opts.compact:
self.ip_req_count['ip'][ip] += 1
self.ip_req_count['request'][requests] += 1
# top ip's or top requests to check
else:
self.dict_add(req_ip, found_time_date,
found_time_hour, found_time_minute)
if opts.request:
# Add ip data from line to dict
self.ip_req_count[req_ip]['ip'][ip] += 1
else:
# add request data from line to dict
self.ip_req_count[req_ip]['get_post'][
requests] += 1
else:
found_time = None
return found_time
def get_data_from_logs(self, logs=None):
""" Process each log file and grab requested data """
opts = self.cmd_args['opts']
args = self.cmd_args['args']
start_time, end_time = (self.data['time_period'][0],
self.data['time_period'][1])
regex_date, regex_requests = self.regex_compile(opts)
first_recorded_date = None
last_recorded_date = None
# sort logs by 'last modified date' to grab earliest and last record
if not opts.select and 'cycle_all' not in self.cmd_args:
logs = [log[0] for log in sorted(
self.data['last_modified'].items(), key=itemgetter(1),
reverse=True)]
log_count = self.data['log_count']
while True:
# Go through each log file and grab required data
for number, logfile in enumerate(logs, 1):
if not opts.select and 'cycle_all' not in self.cmd_args:
# dynamic print update status
stdout.write(
"\r\x1b[K" + "Checking log file {0}/{1}... "
"{2} ({3})".format(
number, log_count, logfile,
self.data['logs'][logfile]))
stdout.flush()
sleep(1)
gzip_file_check = (True if logfile.endswith('.gz') else False)
if gzip_file_check:
# read gzip files
infile = self.openfile(logfile)
for line in infile:
found_time = self.evaluate_line(line, start_time,
end_time,
regex_date,
regex_requests,
opts, args)
# Once we find the end date time we no longer
# need to carry on checking lines.
if found_time:
self.hit_count += 1
last_recorded_date = found_time
if not first_recorded_date:
first_recorded_date = found_time
if found_time >= end_time:
break
elif opts.top:
# read log file from top to bottom.
with self.openfile(logfile) as infile:
for line in infile:
found_time = self.evaluate_line(line, start_time,
end_time,
regex_date,
regex_requests,
opts, args)
if found_time:
self.hit_count += 1
last_recorded_date = found_time
if not first_recorded_date:
first_recorded_date = found_time
if found_time >= end_time:
break
# read log file from top line to the bottom completely
elif opts.complete:
with self.openfile(logfile) as infile:
for line in infile:
found_time = self.evaluate_line(line, start_time,
end_time,
regex_date,
regex_requests,
opts, args)
if found_time:
self.hit_count += 1
last_recorded_date = found_time
if not first_recorded_date: