Network monitoring is a critical part of cybersecurity. Knowing which hosts are up, which ports are open, and when unexpected changes occur can prevent security incidents before they escalate. With Python, you can create scripts that perform scans, log results, and even send notifications — all with minimal tools.
This post will walk through a practical example, including code snippets, to demonstrate real-world cybersecurity automation.
Step 1: Setting Up the Environment
First, make sure you have Python 3.x installed. Then, set up a virtual environment and install the necessary packages:
# Create a virtual environment
python3 -m venv netmon-env
# Activate the environment (Mac/Linux)
source netmon-env/bin/activate
# Activate the environment (Windows)
netmon-env\Scripts\activate
# Install required packages
pip install python-nmap requests
Step 2: Scanning Hosts and Ports
We’ll use the python-nmap module to scan hosts on our local network for common open ports:
import nmap
# Initialize scanner
scanner = nmap.PortScanner()
# Scan a target IP range for ports 22, 80, 443
scanner.scan('192.168.1.0/24', '22,80,443')
# Print results
for host in scanner.all_hosts():
print(f'Host: {host}, State: {scanner[host].state()}')
for proto in scanner[host].all_protocols():
print(f'Protocol: {proto}')
ports = scanner[host][proto].keys()
for port in ports:
print(f'Port {port}: {scanner[host][proto][port]["state"]}')
This simple script allows you to quickly see which hosts are live and which ports are open, giving you insight into potential vulnerabilities.
Step 3: Logging Results
Keeping logs of your scans is essential for tracking changes over time. Here’s how you can write scan results to a CSV file:
import csv
with open('network_log.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Host', 'Protocol', 'Port', 'State'])
for host in scanner.all_hosts():
for proto in scanner[host].all_protocols():
ports = scanner[host][proto].keys()
for port in ports:
writer.writerow([host, proto, port, scanner[host][proto][port]['state']])
Now you have a persistent record of your network state that you can review or share with your team.
Step 4: Sending Alerts
Automation becomes powerful when your script can notify you of unusual events. Here’s an example of sending a Slack alert if a critical port (like SSH 22) is unexpectedly open:
import requests
webhook_url = 'https://hooks.slack.com/services/XXX/YYY/ZZZ'
for host in scanner.all_hosts():
if scanner[host].has_tcp(22) and scanner[host]['tcp'][22]['state'] == 'open':
message = {'text': f'Alert: SSH port open on host {host}!'}
requests.post(webhook_url, json=message)
With this setup, you’ll be instantly notified of potential risks — an essential feature for any security professional.
Step 5: Putting It All Together
You now have the building blocks for a basic network monitoring tool:
Scan your network for live hosts and open ports.
Log results for historical tracking.
Send alerts for critical issues.
From here, you can expand the script with:
Scheduled scans using cron or Windows Task Scheduler
More detailed vulnerability checks using additional modules
Email notifications with smtplib
Integration with dashboards like Grafana for visualization
Takeaway
This project demonstrates how Python can turn a repetitive, manual security task into an automated workflow. Even at a beginner-intermediate level, these skills showcase your technical ability, problem-solving mindset, and practical approach to cybersecurity.
Tip: Including multiple working code snippets like this in your portfolio shows prospective employers or collaborators that you can build real-world tools, not just talk about theory.
Top comments (0)