I'll help you create a Python script that implements this network monitoring system. The script will use parallel processing for pings and maintain the monitoring state as specified.
import subprocess
import time
from datetime import datetime, timedelta
import threading
from collections import defaultdict
import sys
from typing import Dict, List, Set, Tuple
import colorama
from colorama import Fore, Style
class Node:
def __init__(self, hostname: str):
self.hostname = hostname
self.parent = None
self.children = set()
self.min_latency = float('inf')
self.max_latency = float('-inf')
self.avg_latency = 0
self.total_pings = 0
self.timeouts = []
class NetworkMonitor:
def __init__(self):
self.nodes: Dict[str, Node] = {}
self.monitored_nodes: Set[str] = set()
self.probed_nodes: Set[str] = set()
self.roots: Set[str] = set()
colorama.init()
def build_tree(self, filename: str):
with open(filename, 'r') as f:
for line in f:
hosts = line.strip().split()
if not hosts:
continue
# Create nodes if they don't exist
for host in hosts:
if host not in self.nodes:
self.nodes[host] = Node(host)
# Build relationships
for i in range(len(hosts) - 1):
parent = self.nodes[hosts[i]]
child = self.nodes[hosts[i + 1]]
parent.children.add(child.hostname)
child.parent = parent.hostname
# Add root
self.roots.add(hosts[0])
# Initially monitor all leaf nodes
for node in self.nodes.values():
if not node.children:
self.monitored_nodes.add(node.hostname)
def ping(self, hostname: str) -> Tuple[bool, float]:
try:
cmd = ['ping', '-c', '1', '-W', '1', hostname]
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, text=True)
if 'time=' in output:
latency = float(output.split('time=')[1].split()[0])
return True, latency
return False, 0
except:
return False, 0
def update_node_stats(self, hostname: str, is_up: bool, latency: float):
node = self.nodes[hostname]
if is_up:
node.min_latency = min(node.min_latency, latency)
node.max_latency = max(node.max_latency, latency)
node.total_pings += 1
node.avg_latency = ((node.avg_latency * (node.total_pings - 1)) + latency) / node.total_pings
else:
node.timeouts.append(datetime.now())
def handle_node_status(self, hostname: str, is_up: bool):
node = self.nodes[hostname]
if hostname in self.monitored_nodes:
if not is_up:
self.monitored_nodes.remove(hostname)
if node.parent and node.parent not in self.monitored_nodes:
self.probed_nodes.add(node.parent)
elif node.children:
self.monitored_nodes.remove(hostname)
for child in node.children:
if child not in self.monitored_nodes:
self.probed_nodes.add(child)
elif hostname in self.probed_nodes:
if is_up:
self.probed_nodes.remove(hostname)
self.monitored_nodes.add(hostname)
if node.parent in self.monitored_nodes:
self.monitored_nodes.remove(node.parent)
else:
self.probed_nodes.remove(hostname)
if node.parent and node.parent not in self.monitored_nodes:
self.probed_nodes.add(node.parent)
def get_node_color(self, hostname: str) -> str:
node = self.nodes[hostname]
now = datetime.now()
if node.timeouts:
last_timeout = node.timeouts[-1]
if now - last_timeout <= timedelta(minutes=10):
return Fore.RED
elif now - last_timeout <= timedelta(minutes=60):
return Fore.YELLOW
elif now - last_timeout <= timedelta(days=1):
return Fore.MAGENTA
return Fore.GREEN
def print_tree(self, root: str, depth: int = 0):
node = self.nodes[root]
color = self.get_node_color(root)
status = "M" if root in self.monitored_nodes else "P" if root in self.probed_nodes else " "
print(f"{' ' * depth}{color}{root} [{status}]{Style.RESET_ALL}")
for child in sorted(node.children):
self.print_tree(child, depth + 1)
def monitor(self):
while True:
threads = []
results = {}
# Ping all monitored and probed nodes in parallel
for hostname in self.monitored_nodes | self.probed_nodes:
thread = threading.Thread(
target=lambda h: results.update({h: self.ping(h)}),
args=(hostname,)
)
threads.append(thread)
thread.start()
# Wait for all pings to complete
for thread in threads:
thread.join()
# Process results
for hostname, (is_up, latency) in results.items():
if hostname in self.monitored_nodes:
self.update_node_stats(hostname, is_up, latency)
self.handle_node_status(hostname, is_up)
# Print current state
print("\n" + "=" * 50)
print(f"Status at {datetime.now()}")
for root in sorted(self.roots):
self.print_tree(root)
print(f"Monitored nodes: {sorted(self.monitored_nodes)}")
print(f"Probed nodes: {sorted(self.probed_nodes)}")
print("=" * 50 + "\n")
time.sleep(1)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python script.py <topology_file>")
sys.exit(1)
monitor = NetworkMonitor()
monitor.build_tree(sys.argv[1])
monitor.monitor()
This script implements all the requested functionality:
- Reads a topology file with the specified format
- Maintains monitored and probed nodes lists
- Tracks min/max/avg latency and timeout timestamps
- Implements the node status transition logic
- Runs parallel pings every second
- Colors nodes based on their timeout history
- Prints the tree using DFS
- Handles multiple roots
- Prevents duplicate entries in monitored/probed lists
To use the script:
- Save your topology in a text file (e.g.,
topology.txt) with the format:
a b c
b d e
- Run the script:
python script.py topology.txt
The script will continuously monitor the network and display the current state, with nodes colored according to their timeout history:
- Red: timeout in last 10 minutes
- Yellow: timeout in last 60 minutes
- Magenta: timeout in last 24 hours
- Green: no recent timeouts
Each node is marked with:
- [M]: Monitored node
- [P]: Probed node
- [ ]: Neither monitored nor probed
The script uses actual ping commands and runs them in parallel using threads for efficiency.