switch-scraper.sh 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. # FORK: with NETPULSE_URL on https, the server's root to verify it against
  33. # (DATA_DIR/tls/ca.pem on the server itself). Never skip verification: the
  34. # push carries the agent token.
  35. CA_ARG=""
  36. [ -n "${NETPULSE_CA:-}" ] && CA_ARG="--cacert ${NETPULSE_CA}"
  37. TOKEN_FILE="${TOKEN_FILE:-/opt/netpulse/${AGENT_SLUG}.token}"
  38. TOKEN="$(cat "$TOKEN_FILE")"
  39. if [ -z "$TOKEN" ]; then
  40. echo "[$AGENT_SLUG] ERROR: token vacío en $TOKEN_FILE" >&2
  41. exit 2
  42. fi
  43. PASS_MD5="$(echo -n "${SWITCH_USER}${SWITCH_PASS}" | md5sum | awk '{print $1}')"
  44. # --- Login: el switch exige POST /login.cgi (user+pass+Response=md5) para
  45. # abrir sesión; la cookie admin=<md5> sola ya no basta (firmware actual).
  46. # La sesión persiste mientras se mantenga el Referer en los GET.
  47. curl -sf -m 10 -o /dev/null -X POST "http://${SWITCH_HOST}/login.cgi" \
  48. -d "username=${SWITCH_USER}&password=${SWITCH_PASS}&Response=${PASS_MD5}" \
  49. -b "admin=${PASS_MD5}" || {
  50. echo "[$AGENT_SLUG] ERROR: login rechazado por el switch" >&2
  51. exit 2
  52. }
  53. # --- Scrapear MAC table ---
  54. HTML_MAC="$(curl -sf -m 10 -b "admin=$PASS_MD5" -H "Referer: http://${SWITCH_HOST}/" \
  55. "http://${SWITCH_HOST}/mac.cgi?page=fwd_tbl" 2>/dev/null)" || {
  56. echo "[$AGENT_SLUG] ERROR: no se pudo obtener la MAC table del switch" >&2
  57. exit 2
  58. }
  59. # Parsear: cada fila <tr>...</tr> tiene 4 <td>: No., MAC, VLAN, Type, Port
  60. # Extraer bloques de fila y sacar MAC (campo 2) + Port (campo 5)
  61. MACS_JSON="{}"
  62. if command -v python3 >/dev/null 2>&1; then
  63. MACS_JSON=$(python3 -c "
  64. import re, sys, json
  65. html = sys.stdin.read()
  66. rows = re.findall(r'<tr>\s*(.*?)\s*</tr>', html, re.S)
  67. macs = {}
  68. for row in rows:
  69. cells = re.findall(r'<td[^>]*>(.*?)</td>', row)
  70. if len(cells) >= 5:
  71. mac = cells[1].strip()
  72. port = cells[4].strip()
  73. if re.match(r'^[0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5}$', mac) and port.isdigit():
  74. macs[mac.upper()] = port
  75. print(json.dumps(macs))
  76. " <<< "$HTML_MAC")
  77. fi
  78. # --- Scrapear port statistics ---
  79. HTML_PORTS="$(curl -sf -m 10 -b "admin=$PASS_MD5" -H "Referer: http://${SWITCH_HOST}/" \
  80. "http://${SWITCH_HOST}/port.cgi?page=stats" 2>/dev/null)" || {
  81. echo "[$AGENT_SLUG] ERROR: no se pudo obtener port statistics del switch" >&2
  82. exit 2
  83. }
  84. PORTS_JSON="[]"
  85. if command -v python3 >/dev/null 2>&1; then
  86. PORTS_JSON=$(python3 -c "
  87. import re, sys, json
  88. html = sys.stdin.read()
  89. ports = []
  90. # Patrones: <td>Port N</td> <td>Enable</td> <td>Link Up/Down</td>
  91. for m in re.finditer(r'<td>Port\s*(\d+)</td>\s*<td>(\w+)</td>\s*<td>(Link\s+\w+)</td>', html):
  92. ports.append({'id': f'lan{m.group(1)}', 'label': f'Port {m.group(1)}', 'up': m.group(3) == 'Link Up'})
  93. print(json.dumps(ports))
  94. " <<< "$HTML_PORTS")
  95. fi
  96. # --- Construir payload y push (pusher externo: kind + interval, #288) ---
  97. TS="$(date +%s)"
  98. PAYLOAD="{\"router\":\"${AGENT_SLUG}\",\"ts\":${TS},\"version\":\"scraper-2.0\",\"kind\":\"external\",\"interval\":${INTERVAL},\"data\":{\"fdb\":{\"macs\":${MACS_JSON},\"ports\":${PORTS_JSON}}}}"
  99. SIG=$(printf '%s' "$PAYLOAD" | openssl dgst -sha256 -hmac "$TOKEN" 2>/dev/null | awk '{print $NF}')
  100. HTTP_CODE=$(curl -s $CA_ARG -o /tmp/${AGENT_SLUG}-response -w '%{http_code}' -m 10 -X POST "${NETPULSE_URL}/api/ingest/agent" \
  101. -H "Content-Type: application/json" \
  102. -H "Authorization: Bearer ${TOKEN}" \
  103. -H "X-Agent-Signature: ${SIG}" \
  104. -d "$PAYLOAD" 2>/dev/null)
  105. if [ "$HTTP_CODE" = "202" ]; then
  106. MAC_COUNT=$(echo "$MACS_JSON" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null || echo "?")
  107. echo "[$AGENT_SLUG] OK: ${MAC_COUNT} MACs, push 202" >&2
  108. else
  109. RESP=$(cat /tmp/${AGENT_SLUG}-response 2>/dev/null)
  110. echo "[$AGENT_SLUG] ERROR: push devolvió ${HTTP_CODE}: ${RESP}" >&2
  111. exit 2
  112. fi