PC windows 10 :
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import re
import json
import logging
from netmiko import ConnectHandler
# ========== CONFIGURACIÓN ==========
UMBRAL_LATENCIA_MS = 3
CONSECUTIVOS_ALTA = 1
COSTO_ALTO = 1000
INTERFAZ = "GigabitEthernet1"
# Credenciales SSH (mismas para todo)
R1_SSH = {
'device_type': 'cisco_ios',
'ip': '2.2.2.2',
'username': 'admin',
'password': 'admin',
'secret': 'cisco',
'timeout': 10,
}
contador_alta = 0
accion_ejecutada = False
def obtener_latencia():
try:
with ConnectHandler(**R1_SSH) as conn:
conn.enable()
output = conn.send_command("ping 1.1.1.1 repeat 5")
match = re.search(r'round-trip min/avg/max = \d+/(\d+)/\d+', output)
if match:
latencia = int(match.group(1))
logging.info(f"Latencia medida: {latencia} ms")
return latencia
else:
logging.error("No se pudo extraer latencia")
return None
except Exception as e:
logging.error(f"Error SSH: {e}")
return None
def cambiar_costo_ospf(nuevo_costo):
try:
with ConnectHandler(**R1_SSH) as conn:
conn.enable()
commands = [f"interface {INTERFAZ}", f"ip ospf cost {nuevo_costo}"]
conn.send_config_set(commands)
logging.info(f"Costo cambiado a {nuevo_costo} en {INTERFAZ} (vía SSH)")
return True
except Exception as e:
logging.error(f"Error cambiando costo por SSH: {e}")
return False
def registrar_evento(accion, detalle):
evento = {
"timestamp": time.time(),
"accion": accion,
"detalle": detalle,
"umbral_ms": UMBRAL_LATENCIA_MS,
"costo_aplicado": COSTO_ALTO if "aumentar" in accion else None
}
try:
with open("eventos_agente.json", "a") as f:
f.write(json.dumps(evento) + "\n")
logging.info("Evento registrado")
except Exception as e:
logging.error(f"No se pudo registrar: {e}")
def main():
global contador_alta, accion_ejecutada
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("--- Iniciando Agente Autónomo de Red ---")
while True:
latencia = obtener_latencia()
if latencia is None:
time.sleep(10)
continue
if latencia > UMBRAL_LATENCIA_MS:
contador_alta += 1
logging.warning(f"Latencia alta ({latencia} ms) - cuenta: {contador_alta}")
else:
if accion_ejecutada:
logging.info("Latencia normalizada. Revirtiendo costo.")
if cambiar_costo_ospf(10):
accion_ejecutada = False
registrar_evento("revertir_costo", "costo restaurado a 10")
contador_alta = 0
if contador_alta >= CONSECUTIVOS_ALTA and not accion_ejecutada:
logging.info("Ejecutando acción: aumentar costo OSPF.")
if cambiar_costo_ospf(COSTO_ALTO):
accion_ejecutada = True
registrar_evento("aumentar_costo", f"latencia {latencia} ms")
else:
contador_alta = 0
time.sleep(10)
if __name__ == "__main__":
main()
R1
interface Loopback0
ip address 1.1.1.1 255.255.255.0
ip ospf 1 area 0
!
interface GigabitEthernet1
ip address 10.10.10.1 255.255.255.252
ip ospf 1 area 0
service-policy output SHAPER
!
interface GigabitEthernet2
ip address 10.10.10.5 255.255.255.252
ip ospf 1 area 0
!
interface GigabitEthernet3
ip address 192.168.10.100 255.255.255.0
ip ospf 1 area 0
router ospf 1
router-id 1.1.1.1
!
R2
interface Loopback2
description My second RESTCONF loopback
ip address 10.2.1.1 255.255.255.0
!
interface GigabitEthernet1
ip address 10.10.10.2 255.255.255.252
ip ospf 1 area 0
ip ospf cost 10
!
interface GigabitEthernet2
ip address 10.10.10.10 255.255.255.252
ip ospf 1 area 0
!
interface GigabitEthernet3
ip dhcp client client-id ascii cisco-5000.0002.0002-Gi3
ip address 192.168.100.100 255.255.255.0
ip ospf 1 area 0
!
interface GigabitEthernet4
ip address 192.168.20.100 255.255.255.0
ip ospf 1 area 0
!
router ospf 1
!
ip forward-protocol nd
ip http server
ip http authentication local
ip http secure-server
ip http secure-ciphersuite 3des-ede-cbc-sha aes-128-cbc-sha aes-256-cbc-sha
ip http tls-version TLSv1.2
ip http client source-interface GigabitEthernet3
ip ssh version 2
line con 0
stopbits 1
line vty 0 4
login local
transport input ssh
R3
interface Loopback0
ip address 3.3.3.3 255.255.255.0
ip ospf 1 area 0
!
interface GigabitEthernet1
ip address 10.10.10.6 255.255.255.252
ip ospf 1 area 0
!
interface GigabitEthernet2
ip address 10.10.10.9 255.255.255.252
ip ospf 1 area 0
!
router ospf 1
router-id 3.3.3.3
!
ip forward-protocol nd
ip http server
ip http authentication local
ip http secure-server
line vty 0 4
login local
transport input ssh
!