-
Notifications
You must be signed in to change notification settings - Fork 1
/
driver.py
798 lines (434 loc) · 14.5 KB
/
driver.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
import sys
from AccessLog import *
import json
#print toJson("log-jtmelton.txt")
data = toJson("partial-log-july.txt")
print data
with open('data-Jul.json', 'w') as outfile:
json.dump(data, outfile)
json_to_python = json.loads(data)
######
#print json_to_python['name']
x = json_to_python["9969"]
print x
print x['STATUS']
print len(json_to_python)
#####
per_user = dict()
per_time = dict()
per_size = dict()
per_url = dict()
per_verb = dict()
per_zone = dict()
hostlist = []
hostcounter = dict()
counter = 0
for i in json_to_python:
#print i, json_to_python[i]
y = json_to_python[i]
print "Printing status: " + y['STATUS']
#per_user[y['HOST']].append(y['STATUS'])
if y['HOST'] in per_user:
#val = per_user[y['HOST']]
#val.append(y['STATUS'])
per_user[y['HOST']].append(y['STATUS'])
time = y['TIME']
hr = time.split(":")
per_time[y['HOST']].append(hr[1])
per_size[y['HOST']].append(int(y['SIZE']))
zn = time.split("-")
per_zone[y['HOST']].append(zn[1])
reque = y['REQUEST']
req = reque.split()
per_verb[y['HOST']].append(req[0])
per_url[y['HOST']].append(req[1])
#per_user[y['HOST']] = val
else:
per_user[y['HOST']] = [y['STATUS']]
time = y['TIME']
hr = time.split(":")
per_time[y['HOST']] = [hr[1]]
per_size[y['HOST']] = [int(y['SIZE'])]
zn = time.split("-")
per_zone[y['HOST']] = [zn[1]]
reque = y['REQUEST']
req = reque.split()
per_verb[y['HOST']] = [req[0]]
per_url[y['HOST']] = [req[1]]
hostlist.append(y['HOST'])
#****Ideally use per_user[counter] = [y['STATUS']]
#*****And mapping of counter to ip is already available
#IMP STUFF HERE *******
#hostcounter[counter++]= y['HOST']
print "PRINTING PER_USER: "
print per_user[hostlist[0]]
var = per_user[hostlist[0]]
print sorted(var, reverse = True)
import numpy as np
X = np.array([[0,'0']])
#try to print a particular index of this hostlist
print "*****PRINTING A SAMPLE HOST: " + hostlist[0]
for x in hostlist:
#print x
#print per_user[x]
word_counter = {}
for word in per_user[x]:
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
popular_words = sorted(word_counter, key = word_counter.get, reverse = True)
#top_3 = popular_words[:3]
max_status = popular_words[0]
print x + ": " + max_status
y = x.split(".")
ip = ""
for z in range(4):
l = len(y[z])
l = 3 - l
if(l>0):
#print l
zero = ""
for t in range(3 - len(y[z])):
zero = zero + "0"
y[z] = zero + y[z]
ip = ip + y[z]
#print ip + ": " + max_status
print str(float(float(ip)/1000)) + ": " + max_status
#le = [int(ip),max_status]
le = [float(float(ip)/1000),max_status]
#le = [23, 45]
X = np.vstack([X,le])
print X
##For k-proto analysis:
#from kmodes import kmodes
#from kmodes import kprototypes
#kproto = kprototypes.KPrototypes(n_clusters=4, init='Cao', verbose=2)
#result = kproto.fit_predict(X, categorical= 1)
#print "Printing result:"
#print result
#cluster by status
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import MiniBatchKMeans, KMeans
from sklearn.metrics.pairwise import pairwise_distances_argmin
from sklearn.preprocessing import StandardScaler
###Extract most frequent hour of the day
X = np.array([[0,'0']])
#try to print a particular index of this hostlist
print "*****PRINTING A SAMPLE HOST: " + hostlist[0]
print "*****PRINTING MOST FREQ TIME:****** " + hostlist[0]
for x in hostlist:
#print x
#print per_user[x]
word_counter = {}
for word in per_time[x]:
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
popular_words = sorted(word_counter, key = word_counter.get, reverse = True)
#top_3 = popular_words[:3]
max_time = popular_words[0]
print x + ": " + max_time
y = x.split(".")
ip = ""
for z in range(4):
l = len(y[z])
l = 3 - l
if(l>0):
#print l
zero = ""
for t in range(3 - len(y[z])):
zero = zero + "0"
y[z] = zero + y[z]
ip = ip + y[z]
print str(float(float(ip)/1000)) + ": " + max_time
#le = [int(ip),max_status]
le = [float(float(ip)/1000),max_time]
#le = [23, 45]
X = np.vstack([X,le])
print X
kmeans = KMeans(n_clusters=24, random_state=0).fit(X)
print kmeans.labels_
#cluster by size
##############
#####*****SIZE******####
X = np.array([[0,'0']])
#try to print a particular index of this hostlist
print "*****PRINTING A SAMPLE HOST: " + hostlist[0]
print "*****PRINTING AVG SIZE:****** " + hostlist[0]
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
for x in hostlist:
avg_size = mean(per_size[x])
print x + ": " + str(avg_size)
y = x.split(".")
ip = ""
for z in range(4):
l = len(y[z])
l = 3 - l
if(l>0):
#print l
zero = ""
for t in range(3 - len(y[z])):
zero = zero + "0"
y[z] = zero + y[z]
ip = ip + y[z]
print str(float(float(ip)/1000)) + ": " + str(avg_size)
#le = [int(ip),max_status]
le = [float(float(ip)/1000),avg_size]
#le = [23, 45]
X = np.vstack([X,le])
print X
dend = X
#Print result for size
kmeans = KMeans(n_clusters=24, random_state=0).fit(X)
print kmeans.labels_
#XXXXXXXXXXXXXXXXX
#########SINGLE AND LINKAGE HAC*****#########
#cityblock, euclidean and chebychev: metrics for distance
import numpy as np
import scipy.cluster.hierarchy as hac
import matplotlib.pyplot as plt
fig, axes23 = plt.subplots(2, 3)
for method, axes in zip(['single', 'complete',], axes23):
z = hac.linkage(X, method=method)
# Plotting
axes[0].plot(range(1, len(z)+1), z[::-1, 2])
knee = np.diff(z[::-1, 2], 2)
axes[0].plot(range(2, len(z)), knee)
num_clust1 = knee.argmax() + 2
knee[knee.argmax()] = 0
num_clust2 = knee.argmax() + 2
axes[0].text(num_clust1, z[::-1, 2][num_clust1-1], 'possible\n<- knee point')
part1 = hac.fcluster(z, num_clust1, 'maxclust')
part2 = hac.fcluster(z, num_clust2, 'maxclust')
clr = ['#2200CC' ,'#D9007E' ,'#FF6600' ,'#FFCC00' ,'#ACE600' ,'#0099CC' ,
'#8900CC' ,'#FF0000' ,'#FF9900' ,'#FFFF00' ,'#00CC01' ,'#0055CC']
for part, ax in zip([part1, part2], axes[1:]):
for cluster in set(part):
ax.scatter(X[part == cluster, 0], X[part == cluster, 1],
color=clr[cluster%10])
m = '\n(method: {})'.format(method)
plt.setp(axes[0], title='Screeplot{}'.format(m), xlabel='partition',
ylabel='{}\ncluster distance'.format(m))
plt.setp(axes[1], title='{} Clusters'.format(num_clust1))
plt.setp(axes[2], title='{} Clusters'.format(num_clust2))
plt.tight_layout()
plt.show()
fig, axes23 = plt.subplots(2, 3)
for method, axes in zip(['ward', 'average'], axes23):
z = hac.linkage(X, method=method)
# Plotting
axes[0].plot(range(1, len(z)+1), z[::-1, 2])
knee = np.diff(z[::-1, 2], 2)
axes[0].plot(range(2, len(z)), knee)
num_clust1 = knee.argmax() + 2
knee[knee.argmax()] = 0
num_clust2 = knee.argmax() + 2
axes[0].text(num_clust1, z[::-1, 2][num_clust1-1], 'possible\n<- knee point')
part1 = hac.fcluster(z, num_clust1, 'maxclust')
part2 = hac.fcluster(z, num_clust2, 'maxclust')
clr = ['#2200CC' ,'#D9007E' ,'#FF6600' ,'#FFCC00' ,'#ACE600' ,'#0099CC' ,
'#8900CC' ,'#FF0000' ,'#FF9900' ,'#FFFF00' ,'#00CC01' ,'#0055CC']
for part, ax in zip([part1, part2], axes[1:]):
for cluster in set(part):
ax.scatter(X[part == cluster, 0], X[part == cluster, 1],
color=clr[cluster%10])
m = '\n(method: {})'.format(method)
plt.setp(axes[0], title='Screeplot{}'.format(m), xlabel='partition',
ylabel='{}\ncluster distance'.format(m))
plt.setp(axes[1], title='{} Clusters'.format(num_clust1))
plt.setp(axes[2], title='{} Clusters'.format(num_clust2))
plt.tight_layout()
plt.show()
fig, axes23 = plt.subplots(2, 3)
for method, axes in zip(['centroid','median'], axes23):
z = hac.linkage(X, method=method)
# Plotting
axes[0].plot(range(1, len(z)+1), z[::-1, 2])
knee = np.diff(z[::-1, 2], 2)
axes[0].plot(range(2, len(z)), knee)
num_clust1 = knee.argmax() + 2
knee[knee.argmax()] = 0
num_clust2 = knee.argmax() + 2
axes[0].text(num_clust1, z[::-1, 2][num_clust1-1], 'possible\n<- knee point')
part1 = hac.fcluster(z, num_clust1, 'maxclust')
part2 = hac.fcluster(z, num_clust2, 'maxclust')
clr = ['#2200CC' ,'#D9007E' ,'#FF6600' ,'#FFCC00' ,'#ACE600' ,'#0099CC' ,
'#8900CC' ,'#FF0000' ,'#FF9900' ,'#FFFF00' ,'#00CC01' ,'#0055CC']
for part, ax in zip([part1, part2], axes[1:]):
for cluster in set(part):
ax.scatter(X[part == cluster, 0], X[part == cluster, 1],
color=clr[cluster%10])
m = '\n(method: {})'.format(method)
plt.setp(axes[0], title='Screeplot{}'.format(m), xlabel='partition',
ylabel='{}\ncluster distance'.format(m))
plt.setp(axes[1], title='{} Clusters'.format(num_clust1))
plt.setp(axes[2], title='{} Clusters'.format(num_clust2))
plt.tight_layout()
plt.show()
###########################
#
from matplotlib import pyplot as pl
from scipy.cluster.hierarchy import dendrogram, linkage
import numpy as np
X= dend
pl.scatter(X[:,0], X[:,1])
#plt.show()
Z = linkage(X, 'ward')
# calculate full dendrogram
pl.figure(figsize=(25, 10))
pl.title('Hierarchical Clustering Dendrogram: Ward linkage')
pl.xlabel('sample index')
pl.ylabel('distance')
dendrogram(
Z,
leaf_rotation=90., # rotates the x axis labels
leaf_font_size=8., # font size for the x axis labels
)
pl.show()
pl.scatter(X[:,0], X[:,1])
#plt.show()
Z = linkage(X, 'single')
# calculate full dendrogram
pl.figure(figsize=(25, 10))
pl.title('Hierarchical Clustering Dendrogram: Single linkage')
pl.xlabel('sample index')
pl.ylabel('distance')
dendrogram(
Z,
leaf_rotation=90., # rotates the x axis labels
leaf_font_size=8., # font size for the x axis labels
)
pl.show()
Z = linkage(X, 'complete')
# calculate full dendrogram
pl.figure(figsize=(25, 10))
pl.title('Hierarchical Clustering Dendrogram: Complete linkage')
pl.xlabel('sample index')
pl.ylabel('distance')
dendrogram(
Z,
leaf_rotation=90., # rotates the x axis labels
leaf_font_size=8., # font size for the x axis labels
)
pl.show()
Z = linkage(X, 'median')
# calculate full dendrogram
pl.figure(figsize=(25, 10))
pl.title('Hierarchical Clustering Dendrogram: Median linkage')
pl.xlabel('sample index')
pl.ylabel('distance')
dendrogram(
Z,
leaf_rotation=90., # rotates the x axis labels
leaf_font_size=8., # font size for the x axis labels
)
pl.show()
Z = linkage(X, 'centroid')
# calculate full dendrogram
pl.figure(figsize=(25, 10))
pl.title('Hierarchical Clustering Dendrogram: Centroid linkage')
pl.xlabel('sample index')
pl.ylabel('distance')
dendrogram(
Z,
leaf_rotation=90., # rotates the x axis labels
leaf_font_size=8., # font size for the x axis labels
)
pl.show()
#SIZE DONE
##############
Y = np.array([[0,'0']])
Z = np.array([[0,'0']])
#to create for time-zone or not?
#try to print a particular index of this hostlist
print "*****PRINTING VERB:*******" + hostlist[0]
for x in hostlist:
#print x
#print per_user[x]
word_counter = {}
for word in per_verb[x]:
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
popular_words = sorted(word_counter, key = word_counter.get, reverse = True)
#top_3 = popular_words[:3]
popular_verb = popular_words[0]
print x + ": " + popular_verb
word_counter = {}
for word in per_url[x]:
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
popular_words = sorted(word_counter, key = word_counter.get, reverse = True)
#top_3 = popular_words[:3]
popular_url = popular_words[0]
print x + ": " + popular_url
y = x.split(".")
ip = ""
for z in range(4):
l = len(y[z])
l = 3 - l
if(l>0):
#print l
zero = ""
for t in range(3 - len(y[z])):
zero = zero + "0"
y[z] = zero + y[z]
ip = ip + y[z]
#print ip + ": " + max_status
print str(float(float(ip)/1000)) + ": " + popular_verb
#le = [int(ip),max_status]
le = [float(float(ip)/1000), popular_verb]
#le = [23, 45]
X = np.vstack([X,le])
print str(float(float(ip)/1000)) + ": " + popular_url
#le = [int(ip),max_status]
le = [float(float(ip)/1000), popular_url]
#le = [23, 45]
Y = np.vstack([Y,le])
print "Printing VERB"
print X
print "PRINTING URL"
print Y
####do k-proto
##For k-proto analysis:
#from kmodes import kmodes
#from kmodes import kprototypes
#kproto = kprototypes.KPrototypes(n_clusters=4, init='Cao', verbose=2)
#result = kproto.fit_predict(X, categorical= 1)
#print "Printing result for verb:"
#print result
#kproto = kprototypes.KPrototypes(n_clusters=4, init='Cao', verbose=2)
#result = kproto.fit_predict(Y, categorical= 1)
#print "Printing result for url:"
#print result
#Is this okay to go with for one-hot encoding?? on the basis of counter approach. Will it affect distance
#in k-means clustering?? is there need for one-hot encoding here??
#Split time
#x = sent.split(":")
#print x[1]
import numpy as np
X = np.array([[100, 01], [111, 10], [001, 10], [111, 11], [001, 00], [100, 11], [111,01],[100,10], [001,11]])
l = [999,99]
np.vstack([X,l])
X = np.vstack([X,l])
#create dict {hostip: counter} if hostip exists in the dict, ignore, else add the hostip-counter pair and increment counter. one hot encode
#the value corresponding to the ip. same time put the host_ip in array so that its array index is in sync with the counter
#hostcounter = dict()
#counter = 0
#if host in hostcounter:
# continue
#else:
# hostcounter[host] = counter++
#Load data from hson file
#with open('data.json') as data_file:
# data = json.load(data_file)
#can we have more than 2 features while clustering?