switch-scraper.sh 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. #!/bin/bash
  2. # switch-scraper.sh — pusher externo de NetPulse para switches gestionados
  3. # sin SSH (Keephome KP-9000 y clones con web UI mac.cgi/port.cgi).
  4. #
  5. # Extrae la tabla MAC y el estado de bocas de la web del switch y los
  6. # empuja a POST /api/ingest/agent como pusher EXTERNO (kind=external,
  7. # #285/#288): sin agente instalable, con cadencia declarada (interval)
  8. # para que el servidor escale su ventana de frescura.
  9. #
  10. # Configuración: fichero env (default /opt/netpulse/switch-scraper.env,
  11. # permisos 600; ver switch-scraper.env.example). El timer systemd lanza
  12. # este script cada 5 min; su OnUnitActiveSec debe casar con INTERVAL.
  13. #
  14. # Instalación (host de monitorización):
  15. # install -m 0755 switch-scraper.sh /opt/netpulse/switch-scraper.sh
  16. # install -m 0600 switch-scraper.env /opt/netpulse/switch-scraper.env # editado
  17. # # timer: netpulse-switch-scraper.{service,timer} (OnUnitActiveSec=5min)
  18. set -euo pipefail
  19. ENV_FILE="${SWITCH_SCRAPER_ENV:-/opt/netpulse/switch-scraper.env}"
  20. if [ ! -r "$ENV_FILE" ]; then
  21. echo "[switch-scraper] ERROR: no se puede leer $ENV_FILE" >&2
  22. exit 2
  23. fi
  24. # shellcheck source=/dev/null
  25. . "$ENV_FILE"
  26. : "${SWITCH_HOST:?SWITCH_HOST no definido en $ENV_FILE}"
  27. : "${SWITCH_USER:?SWITCH_USER no definido en $ENV_FILE}"
  28. : "${SWITCH_PASS:?SWITCH_PASS no definido en $ENV_FILE}"
  29. : "${AGENT_SLUG:?AGENT_SLUG no definido en $ENV_FILE}"
  30. : "${NETPULSE_URL:=http://127.0.0.1:3000}"
  31. : "${INTERVAL:=300}"
  32. TOKEN_FILE="${TOKEN_FILE:-/opt/netpulse/${AGENT_SLUG}.token}"
  33. TOKEN="$(cat "$TOKEN_FILE")"
  34. if [ -z "$TOKEN" ]; then
  35. echo "[$AGENT_SLUG] ERROR: token vacío en $TOKEN_FILE" >&2
  36. exit 2
  37. fi
  38. PASS_MD5="$(echo -n "${SWITCH_USER}${SWITCH_PASS}" | md5sum | awk '{print $1}')"
  39. # --- Login: el switch exige POST /login.cgi (user+pass+Response=md5) para
  40. # abrir sesión; la cookie admin=<md5> sola ya no basta (firmware actual).
  41. # La sesión persiste mientras se mantenga el Referer en los GET.
  42. curl -sf -m 10 -o /dev/null -X POST "http://${SWITCH_HOST}/login.cgi" \
  43. -d "username=${SWITCH_USER}&password=${SWITCH_PASS}&Response=${PASS_MD5}" \
  44. -b "admin=${PASS_MD5}" || {
  45. echo "[$AGENT_SLUG] ERROR: login rechazado por el switch" >&2
  46. exit 2
  47. }
  48. # --- Scrapear MAC table ---
  49. HTML_MAC="$(curl -sf -m 10 -b "admin=$PASS_MD5" -H "Referer: http://${SWITCH_HOST}/" \
  50. "http://${SWITCH_HOST}/mac.cgi?page=fwd_tbl" 2>/dev/null)" || {
  51. echo "[$AGENT_SLUG] ERROR: no se pudo obtener la MAC table del switch" >&2
  52. exit 2
  53. }
  54. # Parsear: cada fila <tr>...</tr> tiene 4 <td>: No., MAC, VLAN, Type, Port
  55. # Extraer bloques de fila y sacar MAC (campo 2) + Port (campo 5)
  56. MACS_JSON="{}"
  57. if command -v python3 >/dev/null 2>&1; then
  58. MACS_JSON=$(python3 -c "
  59. import re, sys, json
  60. html = sys.stdin.read()
  61. rows = re.findall(r'<tr>\s*(.*?)\s*</tr>', html, re.S)
  62. macs = {}
  63. for row in rows:
  64. cells = re.findall(r'<td[^>]*>(.*?)</td>', row)
  65. if len(cells) >= 5:
  66. mac = cells[1].strip()
  67. port = cells[4].strip()
  68. if re.match(r'^[0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5}$', mac) and port.isdigit():
  69. macs[mac.upper()] = port
  70. print(json.dumps(macs))
  71. " <<< "$HTML_MAC")
  72. fi
  73. # --- Scrapear port statistics ---
  74. HTML_PORTS="$(curl -sf -m 10 -b "admin=$PASS_MD5" -H "Referer: http://${SWITCH_HOST}/" \
  75. "http://${SWITCH_HOST}/port.cgi?page=stats" 2>/dev/null)" || {
  76. echo "[$AGENT_SLUG] ERROR: no se pudo obtener port statistics del switch" >&2
  77. exit 2
  78. }
  79. PORTS_JSON="[]"
  80. if command -v python3 >/dev/null 2>&1; then
  81. PORTS_JSON=$(python3 -c "
  82. import re, sys, json
  83. html = sys.stdin.read()
  84. ports = []
  85. # Patrones: <td>Port N</td> <td>Enable</td> <td>Link Up/Down</td>
  86. for m in re.finditer(r'<td>Port\s*(\d+)</td>\s*<td>(\w+)</td>\s*<td>(Link\s+\w+)</td>', html):
  87. ports.append({'id': f'lan{m.group(1)}', 'label': f'Port {m.group(1)}', 'up': m.group(3) == 'Link Up'})
  88. print(json.dumps(ports))
  89. " <<< "$HTML_PORTS")
  90. fi
  91. # --- Construir payload y push (pusher externo: kind + interval, #288) ---
  92. TS="$(date +%s)"
  93. PAYLOAD="{\"router\":\"${AGENT_SLUG}\",\"ts\":${TS},\"version\":\"scraper-2.0\",\"kind\":\"external\",\"interval\":${INTERVAL},\"data\":{\"fdb\":{\"macs\":${MACS_JSON},\"ports\":${PORTS_JSON}}}}"
  94. SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "$TOKEN" 2>/dev/null | awk '{print $NF}')
  95. HTTP_CODE=$(curl -s -o /tmp/${AGENT_SLUG}-response -w '%{http_code}' -m 10 -X POST "${NETPULSE_URL}/api/ingest/agent" \
  96. -H "Content-Type: application/json" \
  97. -H "Authorization: Bearer ${TOKEN}" \
  98. -H "X-Agent-Signature: ${SIG}" \
  99. -d "$PAYLOAD" 2>/dev/null)
  100. if [ "$HTTP_CODE" = "202" ]; then
  101. MAC_COUNT=$(echo "$MACS_JSON" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null || echo "?")
  102. echo "[$AGENT_SLUG] OK: ${MAC_COUNT} MACs, push 202" >&2
  103. else
  104. RESP=$(cat /tmp/${AGENT_SLUG}-response 2>/dev/null)
  105. echo "[$AGENT_SLUG] ERROR: push devolvió ${HTTP_CODE}: ${RESP}" >&2
  106. exit 2
  107. fi