Cybersecurity isn’t just about scanning for open ports — it’s about identifying unusual patterns and potential threats before they cause damage. By combining Python with AI, you can build a monitoring system that detects anomalies, scores vulnerabilities, and automatically alerts your team. This project demonstrates advanced technical skill and practical application.
Step 1: Preparing Your Environment
You’ll need Python 3.x and a few key libraries for network scanning, data analysis, and machine learning:
# Create a virtual environment
python3 -m venv ai-netmon
source ai-netmon/bin/activate # Mac/Linux
ai-netmon\Scripts\activate # Windows
# Install required packages
pip install python-nmap pandas scikit-learn matplotlib requests
python-nmap for scanning
pandas for organizing scan data
scikit-learn for anomaly detection
matplotlib for visualization
requests for sending alerts
Step 2: Scanning the Network
We start with the same scanning logic as before, but store the results in a DataFrame for AI processing:
import nmap
import pandas as pd
scanner = nmap.PortScanner()
scanner.scan('192.168.1.0/24', '22,80,443')
data = []
for host in scanner.all_hosts():
for port in scanner[host]['tcp'].keys():
data.append({
'host': host,
'port': port,
'state': 1 if scanner[host]['tcp'][port]['state']=='open' else 0
})
df = pd.DataFrame(data)
print(df.head())
This creates a structured dataset ready for anomaly detection.
Step 3: Detecting Anomalies with Isolation Forest
The Isolation Forest algorithm is great for spotting unusual behavior, like unexpected open ports or rogue devices:
from sklearn.ensemble import IsolationForest
# Train Isolation Forest on current network state
model = IsolationForest(contamination=0.1) # ~10% of data considered anomalous
df['anomaly'] = model.fit_predict(df[['state']])
# Flag anomalies
anomalies = df[df['anomaly'] == -1]
print("Anomalous network activity detected:\n", anomalies)
This identifies ports or hosts behaving differently than usual, giving you early warnings before a security incident occurs.
Step 4: Visualization
Visualizing anomalies helps your team quickly grasp the network’s health:
import matplotlib.pyplot as plt
plt.figure(figsize=(10,6))
plt.scatter(df['host'], df['port'], c=df['anomaly'], cmap='coolwarm', s=100)
plt.xlabel('Host')
plt.ylabel('Port')
plt.title('Network Anomalies Detection')
plt.colorbar(label='Anomaly (-1 = Anomalous)')
plt.show()
Red dots represent anomalies
Blue dots are normal activity
This gives an intuitive, visual overview of your network.
Step 5: Automated Alerts
Combine anomaly detection with Slack or email alerts:
import requests
webhook_url = 'https://hooks.slack.com/services/XXX/YYY/ZZZ'
for _, row in anomalies.iterrows():
message = {
'text': f"Alert: Anomaly detected on host {row['host']}, port {row['port']}!"
}
requests.post(webhook_url, json=message)
Now your team receives instant notifications for unusual activity.
Step 6: Scaling and Next Steps
Once working, you can:
Schedule scans with cron or Task Scheduler
Integrate CVE databases to assign risk scores to anomalous ports
Add more features like geolocation for external IPs or multi-network monitoring
Train machine learning models over time to improve anomaly detection accuracy
Takeaway
This AI-enhanced network monitoring script demonstrates:
Automated scanning and data collection
Machine learning-based anomaly detection
Visualization of network health
Real-time alerting for critical issues
It’s a strong portfolio project because it combines Python, cybersecurity, and AI, showing you can solve complex problems and create actionable solutions.
Pro Tip: Share the full notebook or repository publicly. Employers love seeing working code, visual outputs, and automated systems that solve real-world problems.
Top comments (0)