Notifications
Clear all
Topic starter 17/08/2025 6:08 pm
Here’s a complete example of a simple AI-powered Intrusion Prevention System (IPS) written in Python. This system uses a machine learning model to detect potentially malicious network traffic and block it. We’ll simulate traffic data for demonstration purposes, but the structure is designed to be extensible for real-world use.
🗂 Folder Structure
ai_ips/
├── data/
│ └── traffic_log.csv
├── models/
│ └── intrusion_model.pkl
├── src/
│ ├── __init__.py
│ ├── data_loader.py
│ ├── model_trainer.py
│ ├── predictor.py
│ └── firewall.py
├── main.py
└── README.md
📄 File: data/traffic_log.csv
Simulated traffic data (you can replace this with real packet logs):
duration,protocol,src_bytes,dst_bytes,label
10,tcp,100,200,normal
5,udp,300,100,malicious
2,tcp,50,400,normal
8,icmp,500,50,malicious
📄 File: src/data_loader.py
import pandas as pd
def load_data(path):
df = pd.read_csv(path)
X = df.drop("label", axis=1)
y = df["label"]
return X, y
📄 File: src/model_trainer.py
from sklearn.ensemble import RandomForestClassifier
import joblib
def train_model(X, y, model_path):
model = RandomForestClassifier()
model.fit(X, y)
joblib.dump(model, model_path)
print(f"Model saved to {model_path}")
📄 File: src/predictor.py
import joblib
import pandas as pd
def predict_traffic(model_path, traffic_sample):
model = joblib.load(model_path)
df = pd.DataFrame([traffic_sample])
prediction = model.predict(df)[0]
return prediction
📄 File: src/firewall.py
def block_traffic():
print("🚨 Intrusion detected! Blocking traffic...")
def allow_traffic():
print("✅ Traffic allowed.")
📄 File: main.py
from src.data_loader import load_data
from src.model_trainer import train_model
from src.predictor import predict_traffic
from src.firewall import block_traffic, allow_traffic
DATA_PATH = "data/traffic_log.csv"
MODEL_PATH = "models/intrusion_model.pkl"
# Step 1: Train the model
X, y = load_data(DATA_PATH)
train_model(X, y, MODEL_PATH)
# Step 2: Simulate new traffic
new_sample = {
"duration": 6,
"protocol": "udp",
"src_bytes": 250,
"dst_bytes": 150
}
# Step 3: Predict and act
prediction = predict_traffic(MODEL_PATH, new_sample)
if prediction == "malicious":
block_traffic()
else:
allow_traffic()
📄 File: README.md
# AI Intrusion Prevention System
This is a simple AI-powered IPS that uses machine learning to detect and block malicious traffic.
## Features
- Trainable model using labeled traffic data
- Real-time prediction and prevention
- Modular design for easy extension
## How to Run
1. Place traffic data in `data/traffic_log.csv`
2. Run `main.py` to train and simulate detection