-
Notifications
You must be signed in to change notification settings - Fork 0
/
MininetIDS.py
executable file
·1670 lines (1407 loc) · 60.8 KB
/
MininetIDS.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
import cmd
import os
import shutil
import pandas as pd
from datetime import datetime
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix, accuracy_score
import joblib
import subprocess
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.impute import SimpleImputer
from scipy.stats import pearsonr
import numpy as np
import threading
import time
import configparser
GREEN = '\033[92m'
RESET = '\033[0m'
class Dataset:
def __init__(self, dataset_dir):
self.dataset_dir = dataset_dir
self.datasets = self.load_datasets()
self.selected_dataset = None
self.selected_dataset_name = None
def load_datasets(self):
datasets = {}
for filename in os.listdir(self.dataset_dir):
if filename.endswith(".csv"):
key = os.path.splitext(filename)[0]
path = os.path.join(self.dataset_dir, filename)
datasets[key] = path
return datasets
def import_dataset(self, key, path, move=False):
if not os.path.exists(path):
print("File does not exist.")
return
if not path.lower().endswith('.csv'):
print("Only CSV files are supported.")
return
print("Importing dataset... Please wait.")
loading_thread = threading.Thread(
target=self._import_dataset, args=(key, path, move))
loading_thread.start()
while loading_thread.is_alive():
print(".", end='', flush=True)
time.sleep(0.1)
loading_thread.join()
print("\nDataset '{}' imported successfully!".format(key))
def _import_dataset(self, key, path, move):
dest_path = os.path.join(self.dataset_dir, os.path.basename(path))
if move:
shutil.move(path, dest_path)
else:
shutil.copy(path, dest_path)
self.datasets[key] = dest_path
temp_df = pd.read_csv(path)
dataset_name = os.path.splitext(os.path.basename(path))[0]
features_info_path = f'./datasets/features_info_{dataset_name}.txt'
with open(features_info_path, 'w') as f:
f.write("Features:\n")
for feature in temp_df.columns:
f.write(f"{feature}\n")
def remove_dataset(self, key):
if key in self.datasets:
dataset_path = self.datasets[key]
os.remove(dataset_path)
del self.datasets[key]
print(f"Dataset '{key}' removed.")
else:
print("Dataset not found.")
def select_dataset(self, key):
if key in self.datasets:
dataset_path = self.datasets[key]
print("Loading dataset... Please wait.")
loading_thread = threading.Thread(
target=self._load_dataset, args=(dataset_path,))
loading_thread.start()
while loading_thread.is_alive():
print(".", end='', flush=True)
time.sleep(0.1)
loading_thread.join()
print("\nDataset '{}' selected.".format(key))
else:
print("Dataset not found.")
def _load_dataset(self, dataset_path):
self.selected_dataset = pd.read_csv(dataset_path)
self.selected_dataset_name = os.path.splitext(
os.path.basename(dataset_path))[0]
def top_rows(self, num, column_name=None):
if self.selected_dataset is not None:
if column_name:
if column_name in self.selected_dataset.columns:
print(self.selected_dataset[[column_name]].head(num))
else:
print(
f"Column '{column_name}' not found in the selected dataset.")
else:
print(self.selected_dataset.head(num))
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
def clear_dataset(self):
if hasattr(self, 'selected_dataset'):
delattr(self, 'selected_dataset')
print("Selected dataset cleared.")
else:
print("No dataset selected.")
def clear_all_datasets(self):
for filename in os.listdir(self.dataset_dir):
file_path = os.path.join(self.dataset_dir, filename)
if os.path.isfile(file_path):
os.remove(file_path)
self.datasets = {}
if hasattr(self, 'selected_dataset'):
delattr(self, 'selected_dataset')
print("All datasets cleared.")
def get_column_names_and_types(self):
if self.selected_dataset is not None:
column_names = self.selected_dataset.columns.tolist()
column_types = self.selected_dataset.dtypes.tolist()
return column_names, column_types
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
return [], []
def dataset_summary(self):
if self.selected_dataset is not None:
summary = {}
dataset = self.selected_dataset
summary['rows'], summary['columns'] = dataset.shape
summary['data_types'] = dataset.dtypes
return summary
else:
return None
def remove_outliers(self, threshold):
if self.selected_dataset is not None:
try:
threshold = float(threshold)
print("Removing outliers... Please wait.")
loading_thread = threading.Thread(
target=self._remove_outliers, args=(threshold,))
loading_thread.start()
while loading_thread.is_alive():
print(".", end='', flush=True)
time.sleep(0.1)
loading_thread.join()
print("\nRows containing outliers removed.")
except ValueError as v:
print(v, "Invalid threshold. Please provide a numeric value.")
except Exception as e:
print("An error occurred:", e)
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
def _remove_outliers(self, threshold):
df = self.selected_dataset.copy()
try:
df['flow_id'] = df['flow_id'].str.replace('.', '')
df['ip_src'] = df['ip_src'].str.replace('.', '')
df['ip_dst'] = df['ip_dst'].str.replace('.', '')
df = df.astype("float64")
except:
pass
Q1 = df.quantile(0.25, axis=0)
Q3 = df.quantile(0.75, axis=0)
IQR = Q3 - Q1
lower_bound = Q1 - threshold * IQR
upper_bound = Q3 + threshold * IQR
outlier_rows = ((df < lower_bound) | (df > upper_bound)).any(axis=1)
df_cleaned = df[~outlier_rows]
self.selected_dataset = df_cleaned
def check_missing_values(self, columns=None):
if not hasattr(self, 'selected_dataset'):
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
return None
if not columns:
missing_values = self.selected_dataset.isnull().sum()
print("Missing values in the entire dataset:")
if missing_values.sum() == 0:
print("No missing values found.")
return {}
else:
print(missing_values[missing_values > 0])
return missing_values[missing_values > 0].to_dict()
else:
invalid_columns = [
col for col in columns if col not in self.selected_dataset.columns]
if invalid_columns:
print(f"Invalid columns: {', '.join(invalid_columns)}")
return None
else:
missing_values = self.selected_dataset[columns].isnull().sum()
print(
f"Missing values in specified columns ({', '.join(columns)}):")
if missing_values.sum() == 0:
print("No missing values found in the specified columns.")
return {}
else:
print(missing_values[missing_values > 0])
return missing_values[missing_values > 0].to_dict()
def impute_missing_values(self):
if self.selected_dataset is not None:
print("Imputing missing values... Please wait.")
loading_thread = threading.Thread(
target=self._impute_missing_values)
loading_thread.start()
while loading_thread.is_alive():
print(".", end='', flush=True)
time.sleep(0.1)
loading_thread.join()
print("\nMissing values imputed with mean!")
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
def _impute_missing_values(self):
df = self.selected_dataset.copy()
try:
df['flow_id'] = df['flow_id'].str.replace('.', '')
df['ip_src'] = df['ip_src'].str.replace('.', '')
df['ip_dst'] = df['ip_dst'].str.replace('.', '')
df = df.astype("float64")
except:
pass
imputer_numerical = SimpleImputer(strategy='mean')
df_nd = imputer_numerical.fit_transform(df)
df = pd.DataFrame(df_nd, columns=df.columns)
self.selected_dataset = df
def remove_redundant(self):
if self.selected_dataset is not None:
df = self.selected_dataset.copy()
df.drop_duplicates(inplace=True)
df = df.loc[:, ~df.columns.duplicated()]
self.selected_dataset = df
print("Redundant rows and columns removed.")
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
def unique_values(self, column_name):
if self.selected_dataset is not None:
if column_name in self.selected_dataset.columns:
unique_values = self.selected_dataset[column_name].unique()
print(
f"Unique values in column '{column_name}':\n{unique_values}")
else:
print(
f"Column '{column_name}' not found in the selected dataset.")
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
def drop_unique_columns(self):
if self.selected_dataset is not None:
df = self.selected_dataset.copy()
unique_cols = [
col for col in df.columns if df[col].nunique() == len(df[col])]
if unique_cols:
df.drop(columns=unique_cols, inplace=True)
self.selected_dataset = df
print("Columns with unique values dropped.")
else:
print("No columns with all unique values found in the dataset.")
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
def rename_column(self, current_name, new_name):
if self.selected_dataset is not None:
if current_name in self.selected_dataset.columns:
self.selected_dataset.rename(
columns={current_name: new_name}, inplace=True)
print(f"Column '{current_name}' renamed to '{new_name}'.")
else:
print(f"Column '{current_name}' not found in the dataset.")
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
def remove_columns(self, columns):
if self.selected_dataset is not None:
columns_to_remove = [col.strip() for col in columns]
existing_columns = self.selected_dataset.columns
non_existing = [
col for col in columns_to_remove if col not in existing_columns]
if non_existing:
print(
f"Warning: Columns {', '.join(non_existing)} do not exist in the dataset.")
columns_to_remove = [
col for col in columns_to_remove if col in existing_columns]
if columns_to_remove:
self.selected_dataset = self.selected_dataset.drop(
columns=columns_to_remove)
print(
f"Columns {', '.join(columns_to_remove)} removed successfully.")
else:
print("No valid columns to remove.")
else:
print(
"No dataset selected. Use 'selectDataset' command to select a dataset.")
def map_categorical_to_integer(self, column_name):
if self.selected_dataset is not None:
if column_name in self.selected_dataset.columns:
categories = self.selected_dataset[column_name].unique()
mapping = {}
print("Mapping categories to integers:")
for category in categories:
mapping[category] = input(
f"Enter integer for category '{category}': ")
try:
self.selected_dataset[column_name] = self.selected_dataset[column_name].map(
mapping)
print(
f"Categorical column '{column_name}' mapped to integers.")
except ValueError:
print("Error mapping categories to integers.")
else:
print(f"Column '{column_name}' not found in the dataset.")
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
def one_hot_encoding(self, column_name):
if self.selected_dataset is not None:
if column_name in self.selected_dataset.columns:
try:
self.selected_dataset = pd.get_dummies(
self.selected_dataset, columns=[column_name])
print(
f"One-hot encoding applied to column '{column_name}'.")
except Exception as e:
print(f"Error performing one-hot encoding: {str(e)}")
else:
print(f"Column '{column_name}' not found in the dataset.")
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
def rename_dataset(self, new_name):
if self.selected_dataset is not None:
old_name = self.selected_dataset_name
new_dataset_path = os.path.join(
self.dataset_dir, f"{new_name}.csv")
old_dataset_path = os.path.join(
self.dataset_dir, f"{old_name}.csv")
if os.path.exists(old_dataset_path):
os.rename(old_dataset_path, new_dataset_path)
self.datasets[new_name] = new_dataset_path
del self.datasets[old_name]
self.selected_dataset_name = new_name
print(f"Dataset '{old_name}' has been renamed to '{new_name}'.")
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
def save_dataset(self, key):
if self.selected_dataset is not None:
dataset_path = os.path.join(self.dataset_dir, f"{key}.csv")
self.selected_dataset.to_csv(dataset_path, index=False)
features_info_path = os.path.join(
self.dataset_dir, f"features_info_{key}.txt")
with open(features_info_path, 'w') as f:
f.write("Features:\n")
for feature in self.selected_dataset.columns:
f.write(f"{feature}\n")
print(f"Updated dataset saved as '{key}.csv'.")
else:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
def check_missing_values(self, columns=None):
if self.selected_dataset is None:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
return None
if columns is None:
missing_values = self.selected_dataset.isnull().sum()
print("Missing values in the entire dataset:")
if missing_values.sum() == 0:
print("No missing values found.")
return {}
else:
print(missing_values[missing_values > 0])
return missing_values[missing_values > 0].to_dict()
else:
invalid_columns = [
col for col in columns if col not in self.selected_dataset.columns]
if invalid_columns:
print(f"Invalid columns: {', '.join(invalid_columns)}")
return None
else:
missing_values = self.selected_dataset[columns].isnull().sum()
print(
f"Missing values in specified columns ({', '.join(columns)}):")
if missing_values.sum() == 0:
print("No missing values found in the specified columns.")
return {}
else:
print(missing_values[missing_values > 0])
return missing_values[missing_values > 0].to_dict()
def select_subset(self, columns):
if self.selected_dataset is None:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
return
missing_columns = [
col for col in columns if col not in self.selected_dataset.columns]
if missing_columns:
print(
f"Columns {missing_columns} not found in the selected dataset.")
else:
self.selected_dataset = self.selected_dataset[columns]
print(f"Subset of columns {columns} selected.")
def add_columns(self, new_column_name, columns_to_add):
if self.selected_dataset is None:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
return
missing_columns = [
col for col in columns_to_add if col not in self.selected_dataset.columns]
if missing_columns:
print(
f"Columns {missing_columns} not found in the selected dataset.")
else:
self.selected_dataset[new_column_name] = self.selected_dataset[columns_to_add].sum(
axis=1)
print(
f"New column '{new_column_name}' created by adding columns {columns_to_add}.")
def save_feature_selection(self, dataset_name, selected_features, X_selected, y):
features_info_path = os.path.join(
self.dataset_dir, f"features_info_{dataset_name}.txt")
with open(features_info_path, 'w') as f:
f.write("Selected Features:\n")
for feature in selected_features:
f.write(f"{feature}\n")
print(f"Selected features info saved as '{features_info_path}'.")
dataset_path = os.path.join(self.dataset_dir, f"{dataset_name}.csv")
df_selected = pd.DataFrame(X_selected, columns=selected_features)
df_selected['label'] = y # Add the label column
df_selected.to_csv(dataset_path, index=False)
print(f"Selected features saved as '{dataset_path}'.")
class MachineLearning:
def __init__(self, models_dir):
self.models_dir = models_dir
def train_and_evaluate(self, classifier, X, y, split_ratio, model_name):
print(f"Training {model_name} model... Please wait.")
loading_thread = threading.Thread(target=self._train_and_evaluate_model, args=(
classifier, X, y, split_ratio))
loading_thread.start()
while loading_thread.is_alive():
print(".", end='', flush=True)
time.sleep(0.1)
loading_thread.join()
print(f"\n{model_name} model training and evaluation completed.")
# Print the results
print("Confusion Matrix:\n", self.cm)
print("Accuracy Score: {:.2f}%".format(self.acc * 100))
# Ask about saving the model
save_model = input(
"Do you want to save the trained model? (yes/no): ").strip().lower()
if save_model == 'yes':
model_file = os.path.join(self.models_dir, f"{model_name}.pkl")
joblib.dump(self.classifier, model_file)
print(f"Trained model saved as '{model_file}'.")
features_info_path = os.path.join(os.path.dirname(
self.models_dir), "datasets", f"features_info_{model_name}.txt")
with open(features_info_path, 'w') as f:
f.write("Features:\n")
for feature in X.columns:
f.write(f"{feature}\n")
print(
f"Dataset features (excluding target variable) saved as '{features_info_path}'.")
else:
print("Model not saved.")
def _train_and_evaluate_model(self, classifier, X, y, split_ratio):
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=split_ratio, random_state=0)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
self.cm = confusion_matrix(y_test, y_pred)
self.acc = accuracy_score(y_test, y_pred)
self.classifier = classifier
def train_logistic_regression(self, X, y, split_ratio, dataset_name):
model_name = f"{dataset_name}-logistic_regression"
classifier = LogisticRegression(solver='liblinear', random_state=0)
print("Training Logistic Regression model...")
self.train_and_evaluate(classifier, X, y, split_ratio, model_name)
def train_knn(self, X, y, split_ratio, dataset_name):
model_name = f"{dataset_name}-k_nearest_neighbors"
classifier = KNeighborsClassifier(
n_neighbors=5, metric='minkowski', p=2)
print("Training K Nearest Neighbors model...")
self.train_and_evaluate(classifier, X, y, split_ratio, model_name)
def train_naive_bayes(self, X, y, split_ratio, dataset_name):
model_name = f"{dataset_name}-naive_bayes"
classifier = GaussianNB()
print("Training Naive Bayes model...")
self.train_and_evaluate(classifier, X, y, split_ratio, model_name)
def train_decision_tree(self, X, y, split_ratio, dataset_name):
model_name = f"{dataset_name}-decision_tree"
classifier = DecisionTreeClassifier(
criterion='entropy', random_state=0)
print("Training Decision Tree model...")
self.train_and_evaluate(classifier, X, y, split_ratio, model_name)
def train_random_forest(self, X, y, split_ratio, dataset_name):
model_name = f"{dataset_name}-random_forest"
classifier = RandomForestClassifier(
n_estimators=10, criterion="entropy", random_state=0)
print("Training Random Forest model...")
self.train_and_evaluate(classifier, X, y, split_ratio, model_name)
def feature_selection(self, dataset, num_features):
print("Performing feature selection... Please wait.")
loading_thread = threading.Thread(
target=self._feature_selection, args=(dataset, num_features))
loading_thread.start()
while loading_thread.is_alive():
print(".", end='', flush=True)
time.sleep(0.1)
loading_thread.join()
print("\nFeature selection completed.")
return self.selected_features, self.X_selected, self.y
def _feature_selection(self, dataset, num_features):
if dataset.selected_dataset is None:
print("No dataset selected. Use 'selectDataset' command to select a dataset.")
return
df = dataset.selected_dataset.copy()
# Ask for target variable before starting the process
target = input('Enter the name of target variable: ')
if target not in df.columns:
print(f"Error: '{target}' is not a column in the dataset.")
return
try:
# Convert specific columns if they exist
for col in ['flow_id', 'ip_src', 'ip_dst']:
if col in df.columns:
df[col] = df[col].str.replace('.', '')
# Attempt to convert to float, ignoring errors
df = df.apply(pd.to_numeric, errors='ignore')
except Exception as e:
print(f"Warning: Error in data preprocessing - {str(e)}")
X = df.drop(columns=[target])
y = df[target]
# Handle missing values
imputer_numerical = SimpleImputer(strategy='mean')
X_nd = imputer_numerical.fit_transform(X)
X = pd.DataFrame(X_nd, columns=X.columns)
# Perform feature selection
selector = SelectKBest(
score_func=self.pearson_corr_score, k=num_features)
X_selected = selector.fit_transform(X, y)
selected_feature_indices = selector.get_support(indices=True)
self.selected_features = X.columns[selected_feature_indices].tolist()
self.X_selected = X_selected
self.y = y
def pearson_corr_score(self, X, y):
scores = []
for feature in X.T:
if np.all(feature == feature[0]):
scores.append(0)
else:
corr = pearsonr(feature, y)[0]
scores.append(abs(corr))
return np.nan_to_num(scores)
class Model:
def __init__(self, models_dir):
self.models_dir = models_dir
self.models = self.load_models()
def load_models(self):
models = {}
for filename in os.listdir(self.models_dir):
if filename.endswith(".pkl"):
key = os.path.splitext(filename)[0]
path = os.path.join(self.models_dir, filename)
models[key] = path
return models
def remove_model(self, key):
if key in self.models:
model_path = self.models[key]
os.remove(model_path)
del self.models[key]
print(f"Model '{key}' removed.")
else:
print("Model not found.")
def clear_all_models(self):
for filename in os.listdir(self.models_dir):
file_path = os.path.join(self.models_dir, filename)
os.remove(file_path)
print("All models deleted.")
def import_model(self, key, path):
if not os.path.exists(path):
print("File does not exist.")
return
if not path.lower().endswith('.pkl'):
print("Only PKL files are supported.")
return
dest_path = os.path.join(self.models_dir, os.path.basename(path))
shutil.copy(path, dest_path)
print(f"Model '{key}' imported successfully!")
self.models[key] = dest_path
def export_model(self, model_key, export_path):
if model_key not in self.models:
print("Model not found. Please provide a valid model key.")
return
if not os.path.exists(export_path):
print("Export path does not exist.")
return
model_src_path = self.models[model_key]
model_dest_path = os.path.join(export_path, f"{model_key}.pkl")
shutil.copy(model_src_path, model_dest_path)
print(f"Model '{model_key}' exported to '{export_path}'.")
def list_models(self):
self.models = self.load_models()
if self.models:
print("Available trained models:")
for key in self.models.keys():
print(key)
else:
print("No trained models found.")
class Topology:
def __init__(self, topologies_dir):
self.topologies_dir = topologies_dir
self.topologies = self.load_topologies()
def load_topologies(self):
topologies = {}
for filename in os.listdir(self.topologies_dir):
if filename.endswith(".py"):
key = os.path.splitext(filename)[0]
path = os.path.join(self.topologies_dir, filename)
topologies[key] = path
return topologies
def import_topology(self, key, path):
if not os.path.exists(path):
print("File does not exist.")
return
if not path.lower().endswith('.py'):
print("Only Python files (.py) are supported.")
return
dest_path = os.path.join(self.topologies_dir, os.path.basename(path))
shutil.copy(path, dest_path)
print(f"Topology '{key}' imported successfully!")
self.topologies[key] = dest_path
def remove_topology(self, key):
if key in self.topologies:
topology_path = self.topologies[key]
os.remove(topology_path)
del self.topologies[key]
print(f"Topology '{key}' removed.")
else:
print("Topology not found.")
def start_topology(self, topology_key):
if topology_key in self.topologies:
topology_path = self.topologies[topology_key]
try:
subprocess.run(['gnome-terminal', '--', 'sudo',
'python3', topology_path], check=True)
except subprocess.CalledProcessError as e:
print(f"Error executing the topology: {e}")
else:
print("Topology doesn't exist!")
def clear_mininet(self):
try:
subprocess.run(['sudo', 'mn', '-c'], check=True)
print("Mininet environment cleared.")
except subprocess.CalledProcessError as e:
print(f"Error clearing Mininet environment: {e}")
def describe_topology(self, topology_name):
if topology_name not in self.topologies:
return f"Topology '{topology_name}' not found."
topology_path = self.topologies[topology_name]
try:
with open(topology_path, 'r') as file:
content = file.read()
# Extract the class docstring
class_def_start = content.find("class")
if class_def_start == -1:
return f"No class definition found in {topology_name}"
docstring_start = content.find('"""', class_def_start)
if docstring_start == -1:
return f"No docstring found for the topology class in {topology_name}"
docstring_end = content.find('"""', docstring_start + 3)
if docstring_end == -1:
return f"Docstring not properly closed in {topology_name}"
docstring = content[docstring_start+3:docstring_end].strip()
return f"\nTopology Description for '{topology_name}':\n{docstring}"
except Exception as e:
return f"An error occurred while reading the topology description: {str(e)}"
class Ryu:
def __init__(self):
self.config_file_path = "./ryu-scripts/configurations.conf"
def start_ryu(self):
try:
ryu_script_path = "./ryu-scripts/simple_switch_13.py"
subprocess.Popen(
["gnome-terminal", "--", "ryu-manager", ryu_script_path])
print("Ryu controller started.")
except Exception as e:
print(f"An error occurred: {str(e)}")
def start_ryu_ids(self, model_name):
try:
ryu_script_path = "./ryu-scripts/predictionapp.py"
config = configparser.ConfigParser()
config.read(self.config_file_path)
if 'DEFAULT' not in config:
config['DEFAULT'] = {}
config['DEFAULT']['model'] = model_name
with open(self.config_file_path, "w") as config_file:
config.write(config_file)
subprocess.Popen(["gnome-terminal", "--", "ryu-manager",
ryu_script_path, "--config-file", self.config_file_path])
print("Ryu controller IDS started with model:", model_name)
except Exception as e:
print(f"An error occurred: {str(e)}")
def clear_ryu_buffer(self):
try:
file_path = "./ryu-scripts/PredictFlowStatsfile.csv"
with open(file_path, 'w') as f:
f.truncate(0)
print(f"Content of '{file_path}' cleared.")
except Exception as e:
print(f"An error occurred: {str(e)}")
def set_overwrite_interval(self, overwrite_interval):
try:
config = configparser.ConfigParser()
config.read(self.config_file_path)
if 'DEFAULT' not in config:
config['DEFAULT'] = {}
config['DEFAULT']['overwrite_interval'] = str(overwrite_interval)
with open(self.config_file_path, "w") as config_file:
config.write(config_file)
print("Overwrite interval set to:", overwrite_interval)
except Exception as e:
print(f"An error occurred: {str(e)}")
def set_prediction_delay(self, prediction_delay):
try:
config = configparser.ConfigParser()
config.read(self.config_file_path)
if 'DEFAULT' not in config:
config['DEFAULT'] = {}
config['DEFAULT']['prediction_delay'] = str(prediction_delay)
with open(self.config_file_path, "w") as config_file:
config.write(config_file)
print("Prediction delay set to:", prediction_delay)
except Exception as e:
print(f"An error occurred: {str(e)}")
def get_prediction_delay(self):
try:
config = configparser.ConfigParser()
config.read(self.config_file_path)
return config['DEFAULT'].get('prediction_delay', 'Not set')
except Exception as e:
return f"An error occurred: {str(e)}"
def get_overwrite_interval(self):
try:
config = configparser.ConfigParser()
config.read(self.config_file_path)
return config['DEFAULT'].get('overwrite_interval', 'Not set')
except Exception as e:
return f"An error occurred: {str(e)}"
class MininetIDS(cmd.Cmd):
intro = "Welcome to Mininet-IDS!"
prompt = f"{GREEN}mininet-ids> {RESET}"
def __init__(self):
super().__init__()
self.dataset_dir = "datasets"
self.models_dir = "models"
self.topologies_dir = "topologies"
if not os.path.exists(self.dataset_dir):
os.makedirs(self.dataset_dir)
if not os.path.exists(self.models_dir):
os.makedirs(self.models_dir)
if not os.path.exists(self.topologies_dir):
os.makedirs(self.topologies_dir)
self.dataset = Dataset(self.dataset_dir)
self.model = Model(self.models_dir)
self.topology = Topology(self.topologies_dir)
self.ryu = Ryu()
self.ml = MachineLearning(self.models_dir)
def do_exit(self, arg):
"""
Exits the Mininet-IDS CLI.
Usage: exit
"""
return True
def do_importDataset(self, args):
"""
Imports a dataset into the system.
Usage: importDataset <key> <path> [move]
Parameters:
- key: A unique identifier for the dataset
- path: The file path of the dataset to import
- move (optional): If specified, moves the file instead of copying
The dataset name shouldn't contain any dash (-)
The dataset should be in CSV format.
"""
parts = args.split()
if len(parts) < 2:
print("Usage: importDataset <key> <path> optional: [move]")
return
key, path = parts[:2]
move = len(parts) >= 3 and parts[2].lower() == 'move'
self.dataset.import_dataset(key, path, move)
def do_listDatasets(self, args):
"""
Lists all available datasets in the system.
Usage: listDatasets
"""
if self.dataset.datasets:
print("Available datasets:")
for key in self.dataset.datasets.keys():
print(key)
else:
print("No datasets imported yet.")
def do_removeDataset(self, args):
"""
Removes a specific dataset from the system.
Usage: removeDataset <key>
Parameters:
- key: The identifier of the dataset to remove
"""
if not args:
print("Please provide the key of the dataset to remove.")
return
self.dataset.remove_dataset(args.strip())
def do_selectDataset(self, args):
"""
Selects a dataset for further operations.
Usage: selectDataset <key>
Parameters:
- key: The identifier of the dataset to select
"""
if not args:
print("Please provide the name of the dataset to select.")
return
self.dataset.select_dataset(args.strip())
def do_topRows(self, line):
"""
Displays the first n entries of the selected dataset or a specified column.
Usage:
- topRows <num>
- topRows <num> <column_name>
Parameters:
- num: Number of rows to display
- column_name (optional): Name of the specific column to display
Prerequisite: A dataset must be selected.
"""
args = line.split()
if len(args) == 1:
self.dataset.top_rows(int(args[0]))
elif len(args) == 2:
self.dataset.top_rows(int(args[0]), args[1])
else:
print("Invalid arguments. Use 'topRows num' or 'topRows num column_name'.")
def do_clearDataset(self, args):
"""
Clears the currently selected dataset from memory.
Usage: clearDataset
Prerequisite: A dataset must be selected.
"""
self.dataset.clear_dataset()
def do_clearAllDatasets(self, args):
"""
Clears the currently selected dataset from memory.
Usage: clearDataset
Prerequisite: A dataset must be selected.
"""
self.dataset.clear_all_datasets()
def do_listCols(self, args):
"""
Lists all column names and their data types in the selected dataset.
Usage: listCols
Prerequisite: A dataset must be selected.
"""
column_names, column_types = self.dataset.get_column_names_and_types()
if column_names:
print("Column names and their data types:\n")
for col, col_type in zip(column_names, column_types):
print(f"{col}: {col_type}")
def do_clrscr(self, args):
"""
Clears the screen.
Usage: clrscr
"""
os.system('clear')
def do_datasetSummary(self, args):
"""
Provides a summary of the selected dataset, including number of rows and columns.
Usage: datasetSummary
Prerequisite: A dataset must be selected.
"""
summary = self.dataset.dataset_summary()