Commit
·
80d1fe3
1
Parent(s):
1962a42
Update Sniffer_AI.py
Browse files- Sniffer_AI.py +71 -41
Sniffer_AI.py
CHANGED
|
@@ -1,69 +1,99 @@
|
|
| 1 |
-
import
|
|
|
|
| 2 |
import joblib
|
| 3 |
-
import
|
| 4 |
import os
|
|
|
|
| 5 |
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
-
# Load the saved
|
| 9 |
-
rf_model = joblib.load('rf_model.pkl')
|
| 10 |
|
| 11 |
-
# Define
|
| 12 |
-
|
| 13 |
-
"
|
|
|
|
| 14 |
]
|
| 15 |
|
|
|
|
| 16 |
class_labels = {
|
| 17 |
-
0: "
|
| 18 |
-
1: "
|
| 19 |
-
2: "
|
| 20 |
-
3: "
|
| 21 |
-
4: "
|
| 22 |
-
5: "
|
| 23 |
-
6: "
|
| 24 |
-
7: "
|
| 25 |
}
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
def detect_intrusion(file):
|
| 31 |
-
|
| 32 |
try:
|
| 33 |
-
log_data = pd.read_csv(file.name)
|
| 34 |
except Exception as e:
|
| 35 |
return f"Error reading file: {str(e)}"
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
|
|
|
| 39 |
if missing_features:
|
| 40 |
return f"Missing features in file: {', '.join(missing_features)}"
|
| 41 |
-
|
| 42 |
-
# Extract the feature values (excluding the 'type' column which is the target)
|
| 43 |
-
feature_values = log_data[feature_names].astype(float).values
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
|
| 49 |
-
return log_data[['Prediction']].head().to_string()
|
| 50 |
|
| 51 |
-
# Create
|
| 52 |
iface = gr.Interface(
|
| 53 |
fn=detect_intrusion,
|
| 54 |
-
inputs=[
|
| 55 |
-
|
| 56 |
-
],
|
| 57 |
-
outputs="text",
|
| 58 |
title="Intrusion Detection System",
|
| 59 |
-
description=(
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
Example file structure:
|
| 63 |
date,time,door_state,sphone_signal,label
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
| 66 |
)
|
| 67 |
|
| 68 |
-
# Launch the interface locally for testing
|
| 69 |
iface.launch()
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
import joblib
|
| 4 |
+
import gradio as gr
|
| 5 |
import os
|
| 6 |
+
import tempfile
|
| 7 |
|
| 8 |
+
# Set a custom directory for Gradio's temporary files
|
| 9 |
+
os.environ["GRADIO_TEMP"] = tempfile.mkdtemp()
|
| 10 |
|
| 11 |
+
# Load the saved Random Forest model
|
| 12 |
+
rf_model = joblib.load('rf_model.pkl') # Ensure the correct model path
|
| 13 |
|
| 14 |
+
# Define required numeric features
|
| 15 |
+
numeric_features = [
|
| 16 |
+
"date_numeric", "total_minutes", "seconds",
|
| 17 |
+
"door_state", "sphone_signal", "label"
|
| 18 |
]
|
| 19 |
|
| 20 |
+
# Class labels for attack types
|
| 21 |
class_labels = {
|
| 22 |
+
0: "Normal",
|
| 23 |
+
1: "Backdoor",
|
| 24 |
+
2: "DDoS",
|
| 25 |
+
3: "Injection",
|
| 26 |
+
4: "Password Attack",
|
| 27 |
+
5: "Ransomware",
|
| 28 |
+
6: "Scanning",
|
| 29 |
+
7: "XSS",
|
| 30 |
}
|
| 31 |
|
| 32 |
+
def convert_datetime_features(log_data):
|
| 33 |
+
"""Convert date and time into numeric values."""
|
| 34 |
+
try:
|
| 35 |
+
log_data['date'] = pd.to_datetime(log_data['date'], format='%d-%m-%y', errors='coerce')
|
| 36 |
+
log_data['date_numeric'] = log_data['date'].astype(np.int64) // 10**9
|
| 37 |
+
|
| 38 |
+
time_parsed = pd.to_datetime(log_data['time'], format='%H:%M:%S', errors='coerce')
|
| 39 |
+
log_data['total_minutes'] = (time_parsed.dt.hour * 60) + time_parsed.dt.minute
|
| 40 |
+
log_data['seconds'] = time_parsed.dt.second
|
| 41 |
+
except Exception as e:
|
| 42 |
+
return f"Error processing date/time: {str(e)}"
|
| 43 |
+
|
| 44 |
+
return log_data
|
| 45 |
|
| 46 |
def detect_intrusion(file):
|
| 47 |
+
"""Process log file and predict attack type."""
|
| 48 |
try:
|
| 49 |
+
log_data = pd.read_csv(file.name)
|
| 50 |
except Exception as e:
|
| 51 |
return f"Error reading file: {str(e)}"
|
| 52 |
|
| 53 |
+
log_data = convert_datetime_features(log_data)
|
| 54 |
+
|
| 55 |
+
missing_features = [feature for feature in numeric_features if feature not in log_data.columns]
|
| 56 |
if missing_features:
|
| 57 |
return f"Missing features in file: {', '.join(missing_features)}"
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
try:
|
| 60 |
+
log_data['door_state'] = log_data['door_state'].astype(str).str.strip().replace({'closed': 0, 'open': 1})
|
| 61 |
+
log_data['sphone_signal'] = pd.to_numeric(log_data['sphone_signal'], errors='coerce')
|
| 62 |
+
|
| 63 |
+
feature_values = log_data[numeric_features].astype(float).values
|
| 64 |
+
predictions = rf_model.predict(feature_values)
|
| 65 |
+
except Exception as e:
|
| 66 |
+
return f"Error during prediction: {str(e)}"
|
| 67 |
+
|
| 68 |
+
# Map predictions to specific attack types
|
| 69 |
+
log_data['Prediction'] = [class_labels.get(pred, 'Unknown Attack') for pred in predictions]
|
| 70 |
+
|
| 71 |
+
# Format date for output
|
| 72 |
+
log_data['date'] = log_data['date'].dt.strftime('%Y-%m-%d')
|
| 73 |
+
|
| 74 |
+
# Select final output columns
|
| 75 |
+
output_df = log_data[['date', 'time', 'Prediction']]
|
| 76 |
+
|
| 77 |
+
# Save the output to a CSV file for download
|
| 78 |
+
output_file = "intrusion_results.csv"
|
| 79 |
+
output_df.to_csv(output_file, index=False)
|
| 80 |
|
| 81 |
+
return output_df, output_file
|
|
|
|
| 82 |
|
| 83 |
+
# Create Gradio interface
|
| 84 |
iface = gr.Interface(
|
| 85 |
fn=detect_intrusion,
|
| 86 |
+
inputs=[gr.File(label="Upload Log File (CSV format)")],
|
| 87 |
+
outputs=[gr.Dataframe(label="Intrusion Detection Results"), gr.File(label="Download Predictions CSV")],
|
|
|
|
|
|
|
| 88 |
title="Intrusion Detection System",
|
| 89 |
+
description=(
|
| 90 |
+
"""
|
| 91 |
+
Upload a CSV log file with the following features:
|
|
|
|
| 92 |
date,time,door_state,sphone_signal,label
|
| 93 |
+
Example:
|
| 94 |
+
26-04-19,13:59:20,1,-85,normal
|
| 95 |
+
"""
|
| 96 |
+
)
|
| 97 |
)
|
| 98 |
|
|
|
|
| 99 |
iface.launch()
|