Forum

Notifications
Clear all

Real time A.I. Network Intrusion Prevention System Source Code.

1 Posts
1 Users
0 Reactions
11 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

Let’s extend the AI Intrusion Prevention System to include real-time packet sniffing using 🐍 scapy. This will allow the system to monitor live network traffic and classify packets as malicious or normal using the trained model.


🗂 Updated 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
│   └── sniffer.py
├── main.py
└── README.md

📄 File: src/sniffer.py

from scapy.all import sniff
from src.predictor import predict_traffic
from src.firewall import block_traffic, allow_traffic

MODEL_PATH = "models/intrusion_model.pkl"

def extract_features(packet):
    try:
        proto = packet.proto if hasattr(packet, 'proto') else 0
        src_bytes = len(packet.payload)
        dst_bytes = len(packet) - src_bytes
        duration = 1  # Placeholder for now

        return {
            "duration": duration,
            "protocol": packet.proto if hasattr(packet, 'proto') else "tcp",
            "src_bytes": src_bytes,
            "dst_bytes": dst_bytes
        }
    except Exception as e:
        print(f"Error extracting features: {e}")
        return None

def process_packet(packet):
    features = extract_features(packet)
    if features:
        prediction = predict_traffic(MODEL_PATH, features)
        if prediction == "malicious":
            block_traffic()
        else:
            allow_traffic()

def start_sniffing():
    print("🔍 Starting packet sniffing...")
    sniff(prn=process_packet, store=False)

📄 Updated main.py

from src.data_loader import load_data
from src.model_trainer import train_model
from src.sniffer import start_sniffing

DATA_PATH = "data/traffic_log.csv"
MODEL_PATH = "models/intrusion_model.pkl"

# Train model
X, y = load_data(DATA_PATH)
train_model(X, y, MODEL_PATH)

# Start sniffing
start_sniffing()

⚠️ Notes & Tips

  • Permissions: You’ll need to run the script with elevated privileges (e.g., sudo) to sniff packets.
  • Protocols: You can extend extract_features to handle specific protocols like TCP, UDP, ICMP more accurately.
  • Realistic Features: Consider adding source/destination IPs, ports, flags, etc., for better model accuracy.
  • Model Compatibility: Ensure your training data uses the same feature format as the sniffed packets.


   
Quote
Share: