[]
windows
emacs
fiber
sklearn
go
+
+
+
+
helm
+
+
html
+
+
+
+
+
saml
sails
+
+
+
bitbucket
astro
scipy
f#
+
phpstorm
mvn
+
elixir
f#
+
+
keras
+
!
eslint
+
||
+
fastapi
laravel
dart
puppet
+
+
fedora
xml
postgres
+
+
yaml
tf
===
bbedit
+
+
+
+
spacy
+
+
+
+
+
+
+
+
+
∞
+
+
...
spacy
+
+
+
+
marko
+
svelte
$
sqlite
==
+
kotlin
Ξ»
Back to Blog
πŸ“‘ Telecom Infrastructure Management on Alpine Linux: Network Excellence
Alpine Linux Telecom Infrastructure

πŸ“‘ Telecom Infrastructure Management on Alpine Linux: Network Excellence

Published Jun 18, 2025

Comprehensive tutorial for network engineers to implement telecom infrastructure management systems on Alpine Linux. Perfect for carrier-grade networking, monitoring, and service provisioning!

19 min read
0 views
Table of Contents

πŸ“‘ Telecom Infrastructure Management on Alpine Linux: Network Excellence

Let’s build enterprise-grade telecom infrastructure management systems on Alpine Linux! πŸš€ This comprehensive tutorial shows you how to implement network monitoring, service provisioning, and carrier-grade management tools. Perfect for telecommunications engineers building robust, scalable network infrastructure! 😊

πŸ€” What is Telecom Infrastructure Management?

Telecom Infrastructure Management encompasses the systems, tools, and processes used to monitor, control, and maintain telecommunications networks, including network elements, services, performance metrics, and automated provisioning of carrier-grade services!

Telecom Infrastructure Management is like:

  • πŸ—οΈ Master control center orchestrating massive network operations
  • 🌐 Digital nervous system monitoring every network component in real-time
  • 🎯 Command bridge ensuring seamless communication services worldwide

🎯 What You Need

Before we start, you need:

  • βœ… Alpine Linux system with adequate network connectivity and resources
  • βœ… Understanding of networking protocols, SNMP, and telecom standards
  • βœ… Knowledge of network management principles and monitoring systems
  • βœ… Root access for system configuration and network management tools

πŸ“‹ Step 1: Install Network Management Foundation

Install Core Network Management Tools

Let’s set up the essential network management infrastructure! 😊

What we’re doing: Installing SNMP monitoring, network discovery tools, and management protocols for comprehensive telecom infrastructure oversight.

# Update package list
apk update

# Install SNMP management tools
apk add net-snmp net-snmp-tools net-snmp-dev
apk add snmp-mibs snmpd

# Install network monitoring and discovery
apk add nmap nmap-nping nmap-scripts
apk add tcpdump wireshark-common tshark
apk add iperf3 netperf

# Install network utilities
apk add bind-tools dnsutils
apk add traceroute mtr
apk add netcat-openbsd socat

# Install database systems for data storage
apk add postgresql postgresql-client postgresql-contrib
apk add mariadb mariadb-client
apk add redis

# Install time synchronization
apk add chrony ntp

# Install web server for management interfaces
apk add nginx apache2
apk add php81 php81-fpm php81-pdo php81-mysql

# Install monitoring and metrics collection
apk add prometheus grafana
apk add node-exporter
apk add collectd

# Install automation and scripting tools
apk add python3 python3-dev py3-pip
apk add ansible
apk add perl perl-dev

# Install security and access control
apk add openssh openssh-server
apk add fail2ban
apk add openssl

# Verify core installations
snmpwalk -v2c -c public localhost 1.3.6.1.2.1.1
nmap --version
prometheus --version 2>/dev/null || echo "Prometheus installed"

echo "Network management foundation installed! πŸ“Š"

What this does: πŸ“– Installs complete network management ecosystem with monitoring, discovery, and automation capabilities.

Example output:

SNMPv2-MIB::sysDescr.0 = STRING: Linux alpine-host 5.15.0 #1 SMP
Nmap version 7.93
Network management foundation installed! πŸ“Š

What this means: Alpine Linux is ready for carrier-grade network management! βœ…

Configure SNMP Management Infrastructure

Let’s set up comprehensive SNMP monitoring! 🎯

What we’re doing: Configuring SNMP agents, MIB management, and secure community strings for network device monitoring.

# Create SNMP configuration directory
mkdir -p /etc/snmp/mibs

# Configure SNMP daemon
cat > /etc/snmp/snmpd.conf << 'EOF'
# SNMP Configuration for Telecom Infrastructure Management
# Alpine Linux Network Management System

# System information
sysLocation    Network Operations Center, Alpine Linux
sysContact     [email protected]
sysServices    72

# Community strings (change these in production!)
rocommunity    netmon      default
rwcommunity    netadmin    127.0.0.1

# Security settings
com2sec readonly  default         public
com2sec readwrite localhost       private

group MyROGroup v1         readonly
group MyROGroup v2c        readonly
group MyRWGroup v1         readwrite
group MyRWGroup v2c        readwrite

view all    included  .1                               80
view system included  .1.3.6.1.2.1.1                   
view system included  .1.3.6.1.2.1.25.1                

access MyROGroup ""      any       noauth    exact  all    none   none
access MyRWGroup ""      any       noauth    exact  all    all    all

# Process monitoring
proc  sshd
proc  nginx
proc  postgresql

# Disk monitoring
disk / 10000

# Load monitoring
load 12 14 14

# Network interface monitoring
interface eth0

# Extend SNMP with custom scripts
extend test1 /bin/echo "Test Extension"
extend uptime /usr/bin/uptime
extend df /bin/df -h /

# Logging
[snmp] logOption f /var/log/snmpd.log
EOF

# Configure SNMP client
cat > /etc/snmp/snmp.conf << 'EOF'
# SNMP Client Configuration
mibs +ALL
mibdirs /usr/share/snmp/mibs:/etc/snmp/mibs
EOF

# Create custom MIB directory structure
mkdir -p /etc/snmp/mibs/enterprise
mkdir -p /etc/snmp/mibs/standard

# Download common telecom MIBs (examples)
cat > /etc/snmp/mibs/enterprise/TELECOM-INFRASTRUCTURE-MIB.txt << 'EOF'
TELECOM-INFRASTRUCTURE-MIB DEFINITIONS ::= BEGIN

IMPORTS
    MODULE-IDENTITY, OBJECT-TYPE, enterprises,
    Counter32, Gauge32, TimeTicks FROM SNMPv2-SMI
    DisplayString FROM SNMPv2-TC;

telecomInfrastructure MODULE-IDENTITY
    LAST-UPDATED "202506180000Z"
    ORGANIZATION "Alpine Linux Telecom Management"
    CONTACT-INFO "Network Operations Center"
    DESCRIPTION  "MIB for telecom infrastructure monitoring"
    ::= { enterprises 99999 }

-- Network Elements Group
networkElements OBJECT IDENTIFIER ::= { telecomInfrastructure 1 }

-- Service Monitoring Group  
serviceMonitoring OBJECT IDENTIFIER ::= { telecomInfrastructure 2 }

-- Performance Metrics Group
performanceMetrics OBJECT IDENTIFIER ::= { telecomInfrastructure 3 }

-- Example objects
networkElementCount OBJECT-TYPE
    SYNTAX      Gauge32
    MAX-ACCESS  read-only
    STATUS      current
    DESCRIPTION "Number of managed network elements"
    ::= { networkElements 1 }

serviceAvailability OBJECT-TYPE
    SYNTAX      Gauge32 (0..100)
    MAX-ACCESS  read-only
    STATUS      current
    DESCRIPTION "Overall service availability percentage"
    ::= { serviceMonitoring 1 }

END
EOF

# Start SNMP services
rc-update add snmpd default
service snmpd start

# Configure firewall for SNMP
iptables -A INPUT -p udp --dport 161 -j ACCEPT
iptables -A INPUT -p udp --dport 162 -j ACCEPT

# Test SNMP configuration
snmpwalk -v2c -c public localhost system
snmpget -v2c -c public localhost 1.3.6.1.2.1.1.1.0

echo "SNMP infrastructure configured! πŸ“‘"

What this does: πŸ“– Creates comprehensive SNMP monitoring system with custom MIBs and security configurations.

Example output:

SNMPv2-MIB::sysDescr.0 = STRING: Linux alpine-host 5.15.0
SNMPv2-MIB::sysObjectID.0 = OID: NET-SNMP-MIB::netSnmpAgentOIDs.10
SNMP infrastructure configured! πŸ“‘

What this means: Network elements can be monitored via SNMP! βœ…

πŸ“‹ Step 2: Network Discovery and Topology Management

Implement Automated Network Discovery

Let’s create intelligent network discovery systems! πŸ”

What we’re doing: Building automated network discovery tools that map network topology, discover devices, and maintain real-time network inventories.

# Create network discovery framework
mkdir -p /opt/telecom-mgmt/{discovery,topology,inventory,scripts}

# Create network discovery script
cat > /opt/telecom-mgmt/discovery/network-discovery.py << 'EOF'
#!/usr/bin/env python3
"""
Advanced Network Discovery System for Telecom Infrastructure
Discovers network devices, services, and topology
"""

import subprocess
import json
import socket
import threading
import time
from datetime import datetime
import ipaddress
import sqlite3
import xml.etree.ElementTree as ET

class NetworkDiscovery:
    def __init__(self, config_file="/opt/telecom-mgmt/config/discovery.json"):
        self.config = self.load_config(config_file)
        self.db_path = "/opt/telecom-mgmt/data/network_inventory.db"
        self.init_database()
        
    def load_config(self, config_file):
        """Load discovery configuration"""
        default_config = {
            "scan_ranges": ["192.168.1.0/24", "10.0.0.0/24"],
            "snmp_communities": ["public", "private"],
            "tcp_ports": [22, 23, 80, 443, 161, 162, 8080],
            "discovery_interval": 3600,
            "max_threads": 50,
            "timeout": 5
        }
        try:
            with open(config_file, 'r') as f:
                config = json.load(f)
                return {**default_config, **config}
        except FileNotFoundError:
            return default_config
    
    def init_database(self):
        """Initialize SQLite database for network inventory"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # Create network devices table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS network_devices (
                id INTEGER PRIMARY KEY,
                ip_address TEXT UNIQUE,
                hostname TEXT,
                mac_address TEXT,
                device_type TEXT,
                vendor TEXT,
                model TEXT,
                os_version TEXT,
                snmp_community TEXT,
                last_seen TIMESTAMP,
                status TEXT,
                services TEXT,
                location TEXT,
                description TEXT,
                discovered_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # Create network topology table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS network_topology (
                id INTEGER PRIMARY KEY,
                source_device TEXT,
                destination_device TEXT,
                connection_type TEXT,
                interface_source TEXT,
                interface_destination TEXT,
                bandwidth TEXT,
                discovered_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # Create service inventory table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS service_inventory (
                id INTEGER PRIMARY KEY,
                device_ip TEXT,
                service_name TEXT,
                port INTEGER,
                protocol TEXT,
                status TEXT,
                response_time REAL,
                last_checked TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        conn.commit()
        conn.close()
    
    def ping_host(self, ip):
        """Check if host is reachable via ping"""
        try:
            result = subprocess.run(
                ['ping', '-c', '1', '-W', '2', str(ip)],
                capture_output=True,
                text=True,
                timeout=5
            )
            return result.returncode == 0
        except subprocess.TimeoutExpired:
            return False
    
    def port_scan(self, ip, ports):
        """Scan TCP ports on a host"""
        open_ports = []
        for port in ports:
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(self.config['timeout'])
                result = sock.connect_ex((str(ip), port))
                if result == 0:
                    open_ports.append(port)
                sock.close()
            except Exception:
                pass
        return open_ports
    
    def snmp_query(self, ip, community):
        """Query device via SNMP"""
        try:
            # System description
            result = subprocess.run([
                'snmpget', '-v2c', '-c', community, str(ip),
                '1.3.6.1.2.1.1.1.0'  # sysDescr
            ], capture_output=True, text=True, timeout=10)
            
            if result.returncode == 0:
                sys_descr = result.stdout.strip()
                
                # Get hostname
                hostname_result = subprocess.run([
                    'snmpget', '-v2c', '-c', community, str(ip),
                    '1.3.6.1.2.1.1.5.0'  # sysName
                ], capture_output=True, text=True, timeout=10)
                
                hostname = ""
                if hostname_result.returncode == 0:
                    hostname = hostname_result.stdout.strip()
                
                return {
                    'accessible': True,
                    'community': community,
                    'sys_descr': sys_descr,
                    'hostname': hostname
                }
        except Exception as e:
            pass
        
        return {'accessible': False}
    
    def discover_device(self, ip):
        """Discover a single network device"""
        device_info = {
            'ip_address': str(ip),
            'hostname': '',
            'device_type': 'unknown',
            'vendor': '',
            'model': '',
            'os_version': '',
            'snmp_community': '',
            'status': 'unreachable',
            'services': [],
            'last_seen': datetime.now()
        }
        
        print(f"πŸ” Discovering {ip}...")
        
        # Check if host is reachable
        if not self.ping_host(ip):
            return None
        
        device_info['status'] = 'reachable'
        
        # Try to resolve hostname
        try:
            hostname = socket.gethostbyaddr(str(ip))[0]
            device_info['hostname'] = hostname
        except socket.herror:
            pass
        
        # Port scan
        open_ports = self.port_scan(ip, self.config['tcp_ports'])
        device_info['services'] = open_ports
        
        # SNMP discovery
        for community in self.config['snmp_communities']:
            snmp_result = self.snmp_query(ip, community)
            if snmp_result['accessible']:
                device_info['snmp_community'] = community
                device_info['status'] = 'managed'
                
                # Parse system description for device details
                sys_descr = snmp_result.get('sys_descr', '')
                if 'Linux' in sys_descr:
                    device_info['device_type'] = 'linux_server'
                elif 'Cisco' in sys_descr:
                    device_info['device_type'] = 'cisco_device'
                    device_info['vendor'] = 'Cisco'
                elif 'Juniper' in sys_descr:
                    device_info['device_type'] = 'juniper_device'
                    device_info['vendor'] = 'Juniper'
                
                if snmp_result.get('hostname'):
                    device_info['hostname'] = snmp_result['hostname']
                
                break
        
        return device_info
    
    def save_device(self, device_info):
        """Save device information to database"""
        if not device_info:
            return
            
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            INSERT OR REPLACE INTO network_devices 
            (ip_address, hostname, device_type, vendor, model, os_version,
             snmp_community, last_seen, status, services)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ''', (
            device_info['ip_address'],
            device_info['hostname'],
            device_info['device_type'],
            device_info['vendor'],
            device_info['model'],
            device_info['os_version'],
            device_info['snmp_community'],
            device_info['last_seen'],
            device_info['status'],
            json.dumps(device_info['services'])
        ))
        
        conn.commit()
        conn.close()
    
    def discover_network_range(self, network_range):
        """Discover all devices in a network range"""
        print(f"🌐 Discovering network range: {network_range}")
        
        try:
            network = ipaddress.ip_network(network_range, strict=False)
            threads = []
            
            for ip in network.hosts():
                if len(threads) >= self.config['max_threads']:
                    # Wait for some threads to complete
                    for t in threads[:10]:
                        t.join()
                    threads = threads[10:]
                
                thread = threading.Thread(
                    target=self._discover_and_save_device,
                    args=(ip,)
                )
                thread.start()
                threads.append(thread)
            
            # Wait for all threads to complete
            for thread in threads:
                thread.join()
                
        except Exception as e:
            print(f"❌ Error discovering range {network_range}: {e}")
    
    def _discover_and_save_device(self, ip):
        """Thread worker function"""
        device_info = self.discover_device(ip)
        if device_info and device_info['status'] != 'unreachable':
            self.save_device(device_info)
            print(f"βœ… Discovered: {ip} ({device_info['hostname'] or 'no hostname'}) - {device_info['device_type']}")
    
    def generate_discovery_report(self):
        """Generate discovery report"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('SELECT COUNT(*) FROM network_devices')
        total_devices = cursor.fetchone()[0]
        
        cursor.execute('SELECT COUNT(*) FROM network_devices WHERE status = "managed"')
        managed_devices = cursor.fetchone()[0]
        
        cursor.execute('SELECT device_type, COUNT(*) FROM network_devices GROUP BY device_type')
        device_types = cursor.fetchall()
        
        print(f"\nπŸ“Š Network Discovery Report")
        print(f"===========================")
        print(f"Total devices discovered: {total_devices}")
        print(f"SNMP managed devices: {managed_devices}")
        print(f"\nDevice types:")
        for device_type, count in device_types:
            print(f"  {device_type}: {count}")
        
        conn.close()
    
    def run_discovery(self):
        """Run complete network discovery"""
        print(f"πŸš€ Starting network discovery at {datetime.now()}")
        start_time = time.time()
        
        # Create necessary directories
        import os
        os.makedirs('/opt/telecom-mgmt/data', exist_ok=True)
        os.makedirs('/opt/telecom-mgmt/config', exist_ok=True)
        
        # Discover all configured network ranges
        for network_range in self.config['scan_ranges']:
            self.discover_network_range(network_range)
        
        end_time = time.time()
        discovery_time = end_time - start_time
        
        print(f"\nβœ… Discovery completed in {discovery_time:.2f} seconds")
        self.generate_discovery_report()

if __name__ == "__main__":
    discovery = NetworkDiscovery()
    discovery.run_discovery()
EOF

chmod +x /opt/telecom-mgmt/discovery/network-discovery.py

# Create discovery configuration
mkdir -p /opt/telecom-mgmt/config
cat > /opt/telecom-mgmt/config/discovery.json << 'EOF'
{
    "scan_ranges": [
        "192.168.1.0/24",
        "172.16.0.0/24",
        "10.0.0.0/24"
    ],
    "snmp_communities": ["public", "monitoring", "netmon"],
    "tcp_ports": [22, 23, 25, 53, 80, 110, 143, 443, 993, 995, 161, 162, 514, 8080, 8443],
    "discovery_interval": 3600,
    "max_threads": 30,
    "timeout": 3,
    "enable_topology_discovery": true,
    "enable_service_monitoring": true
}
EOF

# Run initial network discovery
python3 /opt/telecom-mgmt/discovery/network-discovery.py

echo "Network discovery system implemented! πŸ”"

What this does: πŸ“– Creates intelligent network discovery system with device identification, SNMP management, and inventory tracking.

Example output:

πŸš€ Starting network discovery at 2025-06-18 10:00:00
🌐 Discovering network range: 192.168.1.0/24
πŸ” Discovering 192.168.1.1...
βœ… Discovered: 192.168.1.1 (router.local) - cisco_device
Network discovery system implemented! πŸ”

What this means: Network topology is automatically discovered and managed! βœ…

Create Network Topology Visualization

Let’s build network topology mapping and visualization! πŸ—ΊοΈ

What we’re doing: Creating network topology visualization tools that generate network maps, track connections, and provide real-time topology updates.

# Create topology management system
cat > /opt/telecom-mgmt/topology/topology-manager.py << 'EOF'
#!/usr/bin/env python3
"""
Network Topology Management and Visualization
Manages network topology data and generates network maps
"""

import sqlite3
import json
import subprocess
import networkx as nx
import matplotlib.pyplot as plt
from datetime import datetime
import os

class TopologyManager:
    def __init__(self):
        self.db_path = "/opt/telecom-mgmt/data/network_inventory.db"
        self.output_dir = "/opt/telecom-mgmt/topology/maps"
        os.makedirs(self.output_dir, exist_ok=True)
        
    def discover_topology_via_snmp(self):
        """Discover network topology using SNMP"""
        print("πŸ” Discovering network topology via SNMP...")
        
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # Get all managed devices
        cursor.execute('''
            SELECT ip_address, hostname, snmp_community 
            FROM network_devices 
            WHERE status = 'managed' AND snmp_community != ''
        ''')
        devices = cursor.fetchall()
        
        topology_data = []
        
        for device_ip, hostname, community in devices:
            print(f"πŸ“‘ Querying {device_ip} ({hostname})...")
            
            # Get ARP table
            arp_result = self.get_arp_table(device_ip, community)
            topology_data.extend(arp_result)
            
            # Get routing table
            route_result = self.get_routing_table(device_ip, community)
            topology_data.extend(route_result)
            
            # Get interface information
            interface_result = self.get_interface_info(device_ip, community)
            topology_data.extend(interface_result)
        
        # Save topology data
        self.save_topology_data(topology_data)
        conn.close()
        
        return topology_data
    
    def get_arp_table(self, device_ip, community):
        """Get ARP table from device"""
        connections = []
        try:
            # SNMP walk for ARP table
            result = subprocess.run([
                'snmpwalk', '-v2c', '-c', community, device_ip,
                '1.3.6.1.2.1.4.22.1.2'  # ipNetToMediaPhysAddress
            ], capture_output=True, text=True, timeout=30)
            
            if result.returncode == 0:
                lines = result.stdout.strip().split('\n')
                for line in lines:
                    if 'ipNetToMediaPhysAddress' in line:
                        # Parse ARP entry
                        parts = line.split('=')
                        if len(parts) >= 2:
                            oid_part = parts[0].strip()
                            mac_part = parts[1].strip()
                            
                            # Extract IP from OID
                            ip_octets = oid_part.split('.')[-4:]
                            if len(ip_octets) == 4:
                                neighbor_ip = '.'.join(ip_octets)
                                connections.append({
                                    'source': device_ip,
                                    'destination': neighbor_ip,
                                    'connection_type': 'layer2',
                                    'method': 'arp'
                                })
        except Exception as e:
            print(f"⚠️  ARP discovery failed for {device_ip}: {e}")
        
        return connections
    
    def get_routing_table(self, device_ip, community):
        """Get routing table from device"""
        connections = []
        try:
            # SNMP walk for routing table
            result = subprocess.run([
                'snmpwalk', '-v2c', '-c', community, device_ip,
                '1.3.6.1.2.1.4.21.1.7'  # ipRouteNextHop
            ], capture_output=True, text=True, timeout=30)
            
            if result.returncode == 0:
                lines = result.stdout.strip().split('\n')
                for line in lines:
                    if 'ipRouteNextHop' in line:
                        # Parse route entry
                        parts = line.split('=')
                        if len(parts) >= 2:
                            next_hop = parts[1].strip().split(':')[-1].strip()
                            if next_hop and next_hop != '0.0.0.0':
                                connections.append({
                                    'source': device_ip,
                                    'destination': next_hop,
                                    'connection_type': 'layer3',
                                    'method': 'routing'
                                })
        except Exception as e:
            print(f"⚠️  Routing discovery failed for {device_ip}: {e}")
        
        return connections
    
    def get_interface_info(self, device_ip, community):
        """Get interface information from device"""
        interfaces = []
        try:
            # Get interface descriptions
            result = subprocess.run([
                'snmpwalk', '-v2c', '-c', community, device_ip,
                '1.3.6.1.2.1.2.2.1.2'  # ifDescr
            ], capture_output=True, text=True, timeout=30)
            
            if result.returncode == 0:
                print(f"  πŸ“Š Found interfaces on {device_ip}")
                # Interface data would be processed here
                # This is a simplified version
                
        except Exception as e:
            print(f"⚠️  Interface discovery failed for {device_ip}: {e}")
        
        return interfaces
    
    def save_topology_data(self, topology_data):
        """Save topology data to database"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # Clear old topology data
        cursor.execute('DELETE FROM network_topology')
        
        # Insert new topology data
        for connection in topology_data:
            cursor.execute('''
                INSERT INTO network_topology
                (source_device, destination_device, connection_type, interface_source, interface_destination)
                VALUES (?, ?, ?, ?, ?)
            ''', (
                connection['source'],
                connection['destination'],
                connection['connection_type'],
                connection.get('interface_source', ''),
                connection.get('interface_destination', '')
            ))
        
        conn.commit()
        conn.close()
        
        print(f"βœ… Saved {len(topology_data)} topology connections")
    
    def generate_network_map(self, output_format='png'):
        """Generate network topology map"""
        print("πŸ—ΊοΈ  Generating network topology map...")
        
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # Get all devices
        cursor.execute('SELECT ip_address, hostname, device_type FROM network_devices')
        devices = cursor.fetchall()
        
        # Get all connections
        cursor.execute('SELECT source_device, destination_device, connection_type FROM network_topology')
        connections = cursor.fetchall()
        
        # Create network graph
        G = nx.Graph()
        
        # Add nodes (devices)
        for ip, hostname, device_type in devices:
            label = hostname if hostname else ip
            G.add_node(ip, label=label, device_type=device_type)
        
        # Add edges (connections)
        for source, dest, conn_type in connections:
            if source in G.nodes and dest in G.nodes:
                G.add_edge(source, dest, connection_type=conn_type)
        
        # Generate visualization
        plt.figure(figsize=(16, 12))
        
        # Create layout
        pos = nx.spring_layout(G, k=3, iterations=50)
        
        # Draw different device types with different colors
        device_colors = {
            'cisco_device': 'lightblue',
            'juniper_device': 'lightgreen',
            'linux_server': 'lightcoral',
            'unknown': 'lightgray'
        }
        
        for device_type, color in device_colors.items():
            device_nodes = [node for node, data in G.nodes(data=True) 
                          if data.get('device_type') == device_type]
            nx.draw_networkx_nodes(G, pos, nodelist=device_nodes, 
                                 node_color=color, node_size=1000, alpha=0.8)
        
        # Draw edges
        nx.draw_networkx_edges(G, pos, alpha=0.6, width=2)
        
        # Draw labels
        labels = {node: data['label'] for node, data in G.nodes(data=True)}
        nx.draw_networkx_labels(G, pos, labels, font_size=10, font_weight='bold')
        
        plt.title(f"Network Topology Map - Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", 
                 fontsize=16, fontweight='bold')
        plt.axis('off')
        
        # Create legend
        legend_elements = [plt.Rectangle((0,0),1,1, facecolor=color, label=device_type.replace('_', ' ').title())
                          for device_type, color in device_colors.items()]
        plt.legend(handles=legend_elements, loc='upper right')
        
        # Save map
        output_file = f"{self.output_dir}/network_topology_{datetime.now().strftime('%Y%m%d_%H%M%S')}.{output_format}"
        plt.savefig(output_file, dpi=300, bbox_inches='tight')
        plt.close()
        
        print(f"βœ… Network map saved: {output_file}")
        
        conn.close()
        return output_file
    
    def export_topology_json(self):
        """Export topology data as JSON"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # Get devices
        cursor.execute('SELECT * FROM network_devices')
        devices_data = cursor.fetchall()
        devices_columns = [description[0] for description in cursor.description]
        
        # Get topology
        cursor.execute('SELECT * FROM network_topology')
        topology_data = cursor.fetchall()
        topology_columns = [description[0] for description in cursor.description]
        
        # Convert to dictionaries
        devices = [dict(zip(devices_columns, row)) for row in devices_data]
        topology = [dict(zip(topology_columns, row)) for row in topology_data]
        
        export_data = {
            'export_timestamp': datetime.now().isoformat(),
            'devices': devices,
            'topology': topology,
            'statistics': {
                'total_devices': len(devices),
                'total_connections': len(topology),
                'managed_devices': len([d for d in devices if d['status'] == 'managed'])
            }
        }
        
        output_file = f"{self.output_dir}/topology_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        with open(output_file, 'w') as f:
            json.dump(export_data, f, indent=2, default=str)
        
        print(f"βœ… Topology exported: {output_file}")
        conn.close()
        return output_file
    
    def run_topology_discovery(self):
        """Run complete topology discovery process"""
        print("πŸš€ Starting network topology discovery...")
        
        # Discover topology
        self.discover_topology_via_snmp()
        
        # Generate visualization
        map_file = self.generate_network_map()
        
        # Export data
        json_file = self.export_topology_json()
        
        print(f"\nβœ… Topology discovery completed:")
        print(f"  πŸ“Š Network map: {map_file}")
        print(f"  πŸ“„ JSON export: {json_file}")

if __name__ == "__main__":
    # Install required Python packages
    subprocess.run(['pip3', 'install', 'networkx', 'matplotlib'], check=False)
    
    topology_manager = TopologyManager()
    topology_manager.run_topology_discovery()
EOF

chmod +x /opt/telecom-mgmt/topology/topology-manager.py

# Create web interface for topology visualization
mkdir -p /var/www/html/telecom-mgmt
cat > /var/www/html/telecom-mgmt/topology.html << 'EOF'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Network Topology - Telecom Infrastructure Management</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            margin: 0; 
            padding: 20px; 
            background-color: #f5f5f5; 
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }
        .stat-number {
            font-size: 2em;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .topology-image {
            max-width: 100%;
            height: auto;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        .device-list {
            max-height: 400px;
            overflow-y: auto;
        }
        .device-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .device-status {
            padding: 5px 10px;
            border-radius: 20px;
            color: white;
            font-size: 0.8em;
        }
        .status-managed { background-color: #28a745; }
        .status-reachable { background-color: #ffc107; color: black; }
        .status-unreachable { background-color: #dc3545; }
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }
        .btn:hover {
            opacity: 0.9;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>πŸ“‘ Telecom Infrastructure Management</h1>
            <p>Network Topology and Device Management Dashboard</p>
        </div>
        
        <div class="stats">
            <div class="stat-card">
                <div class="stat-number" id="totalDevices">-</div>
                <div>Total Devices</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="managedDevices">-</div>
                <div>Managed Devices</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="connections">-</div>
                <div>Network Connections</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="lastUpdate">-</div>
                <div>Last Discovery</div>
            </div>
        </div>
        
        <div class="card">
            <h3>πŸ—ΊοΈ Network Topology Map</h3>
            <button class="btn" onclick="refreshTopology()">πŸ”„ Refresh Topology</button>
            <button class="btn" onclick="exportTopology()">πŸ“„ Export Data</button>
            <div id="topologyMap" style="text-align: center; margin-top: 20px;">
                <p>Loading network topology...</p>
            </div>
        </div>
        
        <div class="card">
            <h3>πŸ“Š Network Devices</h3>
            <div class="device-list" id="deviceList">
                <p>Loading device list...</p>
            </div>
        </div>
    </div>
    
    <script>
        // Simulated data loading functions
        function loadTopologyData() {
            // In a real implementation, this would fetch from a backend API
            document.getElementById('totalDevices').textContent = '42';
            document.getElementById('managedDevices').textContent = '38';
            document.getElementById('connections').textContent = '156';
            document.getElementById('lastUpdate').textContent = new Date().toLocaleTimeString();
            
            // Load topology image
            document.getElementById('topologyMap').innerHTML = 
                '<img src="/opt/telecom-mgmt/topology/maps/latest_topology.png" alt="Network Topology" class="topology-image" />';
            
            // Load device list
            const devices = [
                { ip: '192.168.1.1', hostname: 'core-router', type: 'cisco_device', status: 'managed' },
                { ip: '192.168.1.10', hostname: 'access-switch-1', type: 'cisco_device', status: 'managed' },
                { ip: '192.168.1.20', hostname: 'server-01', type: 'linux_server', status: 'reachable' },
                { ip: '192.168.1.30', hostname: 'firewall-01', type: 'security_device', status: 'managed' }
            ];
            
            const deviceListHTML = devices.map(device => `
                <div class="device-item">
                    <div>
                        <strong>${device.hostname}</strong><br>
                        <small>${device.ip} β€’ ${device.type.replace('_', ' ')}</small>
                    </div>
                    <span class="device-status status-${device.status}">${device.status}</span>
                </div>
            `).join('');
            
            document.getElementById('deviceList').innerHTML = deviceListHTML;
        }
        
        function refreshTopology() {
            alert('Refreshing network topology... This would trigger a new discovery scan.');
            // In real implementation: trigger backend topology discovery
        }
        
        function exportTopology() {
            alert('Exporting topology data... This would download a JSON/CSV file.');
            // In real implementation: download exported data
        }
        
        // Load data when page loads
        document.addEventListener('DOMContentLoaded', loadTopologyData);
        
        // Auto-refresh every 5 minutes
        setInterval(loadTopologyData, 300000);
    </script>
</body>
</html>
EOF

echo "Network topology visualization implemented! πŸ—ΊοΈ"

What this does: πŸ“– Creates comprehensive topology discovery and visualization system with web-based management interface.

Example output:

πŸš€ Starting network topology discovery...
πŸ” Discovering network topology via SNMP...
πŸ“‘ Querying 192.168.1.1 (core-router)...
βœ… Saved 45 topology connections
πŸ—ΊοΈ  Generating network topology map...
Network topology visualization implemented! πŸ—ΊοΈ

What this means: Network topology is automatically mapped and visualized! βœ…

πŸ“‹ Step 3: Service Monitoring and Performance Management

Implement Service Performance Monitoring

Let’s create comprehensive service monitoring systems! πŸ“Š

What we’re doing: Building service monitoring infrastructure with performance metrics, SLA tracking, and automated alerting for carrier-grade service assurance.

# Create service monitoring framework
mkdir -p /opt/telecom-mgmt/{monitoring,alerts,reports}

# Create service monitoring system
cat > /opt/telecom-mgmt/monitoring/service-monitor.py << 'EOF'
#!/usr/bin/env python3
"""
Service Performance Monitoring System
Monitors telecom services, tracks SLAs, and generates performance reports
"""

import sqlite3
import json
import time
import threading
import subprocess
import requests
import socket
from datetime import datetime, timedelta
import statistics
import smtplib
from email.mime.text import MimeText
from email.mime.multipart import MimeMultipart

class ServiceMonitor:
    def __init__(self, config_file="/opt/telecom-mgmt/config/monitoring.json"):
        self.config = self.load_config(config_file)
        self.db_path = "/opt/telecom-mgmt/data/service_monitoring.db"
        self.init_database()
        self.alert_manager = AlertManager(self.config.get('alerts', {}))
        
    def load_config(self, config_file):
        """Load monitoring configuration"""
        default_config = {
            "services": [
                {
                    "name": "HTTP Web Service",
                    "type": "http",
                    "url": "http://localhost:80",
                    "expected_response_time": 1000,
                    "check_interval": 60,
                    "timeout": 10,
                    "sla_target": 99.9
                },
                {
                    "name": "SNMP Service",
                    "type": "snmp",
                    "host": "localhost",
                    "community": "public",
                    "oid": "1.3.6.1.2.1.1.1.0",
                    "expected_response_time": 500,
                    "check_interval": 300,
                    "timeout": 5,
                    "sla_target": 99.95
                },
                {
                    "name": "Database Service",
                    "type": "tcp",
                    "host": "localhost",
                    "port": 5432,
                    "expected_response_time": 100,
                    "check_interval": 60,
                    "timeout": 5,
                    "sla_target": 99.9
                }
            ],
            "monitoring_interval": 60,
            "retention_days": 30,
            "alerts": {
                "email_enabled": True,
                "smtp_server": "localhost",
                "smtp_port": 587,
                "from_address": "[email protected]",
                "to_addresses": ["[email protected]"]
            }
        }
        
        try:
            with open(config_file, 'r') as f:
                config = json.load(f)
                return {**default_config, **config}
        except FileNotFoundError:
            # Create default config file
            import os
            os.makedirs(os.path.dirname(config_file), exist_ok=True)
            with open(config_file, 'w') as f:
                json.dump(default_config, f, indent=2)
            return default_config
    
    def init_database(self):
        """Initialize monitoring database"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # Service definitions table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS services (
                id INTEGER PRIMARY KEY,
                name TEXT UNIQUE,
                type TEXT,
                configuration TEXT,
                sla_target REAL,
                created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # Service metrics table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS service_metrics (
                id INTEGER PRIMARY KEY,
                service_name TEXT,
                timestamp TIMESTAMP,
                response_time REAL,
                status TEXT,
                error_message TEXT,
                availability REAL,
                FOREIGN KEY (service_name) REFERENCES services (name)
            )
        ''')
        
        # SLA tracking table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS sla_tracking (
                id INTEGER PRIMARY KEY,
                service_name TEXT,
                period_start TIMESTAMP,
                period_end TIMESTAMP,
                total_checks INTEGER,
                successful_checks INTEGER,
                availability_percentage REAL,
                avg_response_time REAL,
                sla_met BOOLEAN,
                FOREIGN KEY (service_name) REFERENCES services (name)
            )
        ''')
        
        # Alerts table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS alerts (
                id INTEGER PRIMARY KEY,
                service_name TEXT,
                alert_type TEXT,
                severity TEXT,
                message TEXT,
                timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                acknowledged BOOLEAN DEFAULT FALSE,
                resolved BOOLEAN DEFAULT FALSE
            )
        ''')
        
        conn.commit()
        conn.close()
    
    def register_services(self):
        """Register services from configuration"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        for service in self.config['services']:
            cursor.execute('''
                INSERT OR REPLACE INTO services (name, type, configuration, sla_target)
                VALUES (?, ?, ?, ?)
            ''', (
                service['name'],
                service['type'],
                json.dumps(service),
                service.get('sla_target', 99.0)
            ))
        
        conn.commit()
        conn.close()
        print(f"βœ… Registered {len(self.config['services'])} services")
    
    def check_http_service(self, service_config):
        """Check HTTP/HTTPS service"""
        start_time = time.time()
        try:
            response = requests.get(
                service_config['url'],
                timeout=service_config.get('timeout', 10)
            )
            response_time = (time.time() - start_time) * 1000  # Convert to milliseconds
            
            if response.status_code == 200:
                return {
                    'status': 'UP',
                    'response_time': response_time,
                    'error_message': None
                }
            else:
                return {
                    'status': 'DOWN',
                    'response_time': response_time,
                    'error_message': f"HTTP {response.status_code}"
                }
        except Exception as e:
            response_time = (time.time() - start_time) * 1000
            return {
                'status': 'DOWN',
                'response_time': response_time,
                'error_message': str(e)
            }
    
    def check_snmp_service(self, service_config):
        """Check SNMP service"""
        start_time = time.time()
        try:
            result = subprocess.run([
                'snmpget', '-v2c', '-c', service_config['community'],
                service_config['host'], service_config['oid']
            ], capture_output=True, text=True, 
               timeout=service_config.get('timeout', 5))
            
            response_time = (time.time() - start_time) * 1000
            
            if result.returncode == 0:
                return {
                    'status': 'UP',
                    'response_time': response_time,
                    'error_message': None
                }
            else:
                return {
                    'status': 'DOWN',
                    'response_time': response_time,
                    'error_message': result.stderr.strip() or 'SNMP query failed'
                }
        except Exception as e:
            response_time = (time.time() - start_time) * 1000
            return {
                'status': 'DOWN',
                'response_time': response_time,
                'error_message': str(e)
            }
    
    def check_tcp_service(self, service_config):
        """Check TCP service connectivity"""
        start_time = time.time()
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(service_config.get('timeout', 5))
            result = sock.connect_ex((service_config['host'], service_config['port']))
            sock.close()
            
            response_time = (time.time() - start_time) * 1000
            
            if result == 0:
                return {
                    'status': 'UP',
                    'response_time': response_time,
                    'error_message': None
                }
            else:
                return {
                    'status': 'DOWN',
                    'response_time': response_time,
                    'error_message': f"Connection failed to {service_config['host']}:{service_config['port']}"
                }
        except Exception as e:
            response_time = (time.time() - start_time) * 1000
            return {
                'status': 'DOWN',
                'response_time': response_time,
                'error_message': str(e)
            }
    
    def check_service(self, service_config):
        """Check a service based on its type"""
        service_type = service_config['type'].lower()
        
        if service_type == 'http' or service_type == 'https':
            return self.check_http_service(service_config)
        elif service_type == 'snmp':
            return self.check_snmp_service(service_config)
        elif service_type == 'tcp':
            return self.check_tcp_service(service_config)
        else:
            return {
                'status': 'UNKNOWN',
                'response_time': 0,
                'error_message': f"Unknown service type: {service_type}"
            }
    
    def record_metric(self, service_name, result):
        """Record service check result"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        availability = 100.0 if result['status'] == 'UP' else 0.0
        
        cursor.execute('''
            INSERT INTO service_metrics 
            (service_name, timestamp, response_time, status, error_message, availability)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (
            service_name,
            datetime.now(),
            result['response_time'],
            result['status'],
            result['error_message'],
            availability
        ))
        
        conn.commit()
        conn.close()
    
    def calculate_sla_metrics(self, service_name, hours=24):
        """Calculate SLA metrics for a service"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        since_time = datetime.now() - timedelta(hours=hours)
        
        cursor.execute('''
            SELECT response_time, status, availability
            FROM service_metrics
            WHERE service_name = ? AND timestamp >= ?
        ''', (service_name, since_time))
        
        metrics = cursor.fetchall()
        conn.close()
        
        if not metrics:
            return None
        
        response_times = [m[0] for m in metrics if m[0] is not None]
        availabilities = [m[2] for m in metrics]
        
        return {
            'total_checks': len(metrics),
            'successful_checks': len([m for m in metrics if m[1] == 'UP']),
            'availability_percentage': statistics.mean(availabilities) if availabilities else 0,
            'avg_response_time': statistics.mean(response_times) if response_times else 0,
            'max_response_time': max(response_times) if response_times else 0,
            'min_response_time': min(response_times) if response_times else 0
        }
    
    def monitor_service(self, service_config):
        """Monitor a single service continuously"""
        service_name = service_config['name']
        check_interval = service_config.get('check_interval', 60)
        
        print(f"πŸ” Starting monitoring for: {service_name}")
        
        while True:
            try:
                result = self.check_service(service_config)
                self.record_metric(service_name, result)
                
                # Check for alerts
                self.check_service_alerts(service_config, result)
                
                # Log result
                status_emoji = "βœ…" if result['status'] == 'UP' else "❌"
                print(f"{status_emoji} {service_name}: {result['status']} ({result['response_time']:.1f}ms)")
                
                time.sleep(check_interval)
                
            except Exception as e:
                print(f"⚠️  Monitoring error for {service_name}: {e}")
                time.sleep(check_interval)
    
    def check_service_alerts(self, service_config, result):
        """Check if service result triggers alerts"""
        service_name = service_config['name']
        expected_response_time = service_config.get('expected_response_time', 1000)
        
        # Service down alert
        if result['status'] != 'UP':
            self.alert_manager.trigger_alert(
                service_name,
                'SERVICE_DOWN',
                'CRITICAL',
                f"Service {service_name} is DOWN: {result['error_message']}"
            )
        
        # High response time alert
        elif result['response_time'] > expected_response_time:
            self.alert_manager.trigger_alert(
                service_name,
                'HIGH_RESPONSE_TIME',
                'WARNING',
                f"Service {service_name} response time ({result['response_time']:.1f}ms) exceeds threshold ({expected_response_time}ms)"
            )
    
    def generate_service_report(self, hours=24):
        """Generate service performance report"""
        print(f"\nπŸ“Š Service Performance Report - Last {hours} hours")
        print("=" * 60)
        
        for service in self.config['services']:
            service_name = service['name']
            sla_metrics = self.calculate_sla_metrics(service_name, hours)
            
            if sla_metrics:
                sla_target = service.get('sla_target', 99.0)
                sla_met = sla_metrics['availability_percentage'] >= sla_target
                
                print(f"\nπŸ”§ {service_name}")
                print(f"   Availability: {sla_metrics['availability_percentage']:.2f}% (Target: {sla_target}%)")
                print(f"   SLA Status: {'βœ… MET' if sla_met else '❌ VIOLATED'}")
                print(f"   Avg Response Time: {sla_metrics['avg_response_time']:.1f}ms")
                print(f"   Total Checks: {sla_metrics['total_checks']}")
                print(f"   Successful Checks: {sla_metrics['successful_checks']}")
            else:
                print(f"\nπŸ”§ {service_name}")
                print("   No data available")
    
    def start_monitoring(self):
        """Start monitoring all configured services"""
        print("πŸš€ Starting Service Performance Monitoring...")
        
        # Register services in database
        self.register_services()
        
        # Start monitoring threads
        threads = []
        for service_config in self.config['services']:
            thread = threading.Thread(
                target=self.monitor_service,
                args=(service_config,),
                daemon=True
            )
            thread.start()
            threads.append(thread)
        
        print(f"βœ… Started monitoring {len(threads)} services")
        
        try:
            # Generate periodic reports
            while True:
                time.sleep(3600)  # Generate report every hour
                self.generate_service_report()
                
        except KeyboardInterrupt:
            print("\nπŸ›‘ Stopping service monitoring...")
            return

class AlertManager:
    def __init__(self, alert_config):
        self.config = alert_config
        self.db_path = "/opt/telecom-mgmt/data/service_monitoring.db"
    
    def trigger_alert(self, service_name, alert_type, severity, message):
        """Trigger an alert"""
        # Store alert in database
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            INSERT INTO alerts (service_name, alert_type, severity, message)
            VALUES (?, ?, ?, ?)
        ''', (service_name, alert_type, severity, message))
        
        conn.commit()
        conn.close()
        
        # Send alert notification
        if self.config.get('email_enabled', False):
            self.send_email_alert(service_name, alert_type, severity, message)
        
        print(f"🚨 ALERT [{severity}] {service_name}: {message}")
    
    def send_email_alert(self, service_name, alert_type, severity, message):
        """Send email alert notification"""
        try:
            smtp_server = self.config.get('smtp_server', 'localhost')
            smtp_port = self.config.get('smtp_port', 587)
            from_address = self.config.get('from_address', '[email protected]')
            to_addresses = self.config.get('to_addresses', [])
            
            if not to_addresses:
                return
            
            # Create email message
            msg = MimeMultipart()
            msg['From'] = from_address
            msg['To'] = ', '.join(to_addresses)
            msg['Subject'] = f"[{severity}] Telecom Alert: {service_name}"
            
            body = f"""
Telecom Infrastructure Alert

Service: {service_name}
Alert Type: {alert_type}
Severity: {severity}
Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

Message: {message}

This is an automated alert from the Telecom Infrastructure Management System.
"""
            
            msg.attach(MimeText(body, 'plain'))
            
            # Send email
            server = smtplib.SMTP(smtp_server, smtp_port)
            server.send_message(msg)
            server.quit()
            
        except Exception as e:
            print(f"⚠️  Failed to send email alert: {e}")

if __name__ == "__main__":
    import os
    os.makedirs('/opt/telecom-mgmt/data', exist_ok=True)
    os.makedirs('/opt/telecom-mgmt/config', exist_ok=True)
    
    monitor = ServiceMonitor()
    monitor.start_monitoring()
EOF

chmod +x /opt/telecom-mgmt/monitoring/service-monitor.py

echo "Service performance monitoring implemented! πŸ“Š"

What this does: πŸ“– Creates comprehensive service monitoring with SLA tracking, alerting, and performance analysis.

Example output:

πŸš€ Starting Service Performance Monitoring...
βœ… Registered 3 services
βœ… Started monitoring 3 services
πŸ” Starting monitoring for: HTTP Web Service
βœ… HTTP Web Service: UP (45.2ms)
Service performance monitoring implemented! πŸ“Š

What this means: Services are continuously monitored with SLA compliance tracking! βœ…

🎯 Best Practices and Tips

Telecom Infrastructure Management Guidelines

Here are essential management practices:

πŸ”§ Monitoring Best Practices:

  • Implement redundant monitoring systems for critical services
  • Use appropriate check intervals based on service criticality
  • Set realistic SLA targets based on business requirements
  • Monitor both technical and business metrics

⚑ Network Management Optimization:

  • Use SNMP v3 for secure device management
  • Implement automated discovery for dynamic environments
  • Maintain accurate network documentation and topology maps
  • Regular backup of network device configurations

πŸ”’ Security Considerations:

  • Secure SNMP communities and use strong authentication
  • Implement network access control for management systems
  • Regular security audits of network infrastructure
  • Monitor for unauthorized network changes

🌐 Scalability Guidelines:

  • Design monitoring systems for horizontal scaling
  • Use distributed monitoring for large networks
  • Implement proper data retention and archival policies
  • Consider cloud-based management for global networks

πŸŽ‰ Conclusion

Congratulations! You’ve successfully implemented enterprise-grade telecom infrastructure management on Alpine Linux! πŸš€

What we accomplished:

  • βœ… Installed comprehensive network management tools and SNMP infrastructure
  • βœ… Created automated network discovery with device identification and inventory
  • βœ… Implemented network topology mapping and visualization systems
  • βœ… Built service performance monitoring with SLA tracking and alerting
  • βœ… Configured carrier-grade monitoring with real-time metrics collection
  • βœ… Set up automated reporting and performance analysis tools

Your Alpine Linux system now has:

  • πŸ“‘ Enterprise-grade network management capabilities with SNMP monitoring
  • πŸ” Intelligent network discovery and automated device inventory management
  • πŸ—ΊοΈ Real-time network topology visualization and mapping
  • πŸ“Š Comprehensive service monitoring with SLA compliance tracking
  • 🚨 Advanced alerting system with multiple notification channels
  • πŸ“ˆ Performance analytics and reporting for infrastructure optimization

Your Alpine Linux system is now equipped with carrier-grade telecom infrastructure management capabilities, perfect for managing complex network environments, ensuring service quality, and maintaining high availability! 😊

Next steps: Explore advanced network automation, integrate with external management systems, or implement predictive analytics for proactive infrastructure management!