Script de bash en mi Pi hace ping a sitios remotos pero Hermetry guarda un valor sin procesar extraño
Traducido del English por IA ·
Soy analista de datos, no especialista en redes, así que sean amables. Tenemos 7 estaciones de bombeo remotas con módems celulares, y nuestro equipo de operaciones pregunta constantemente «¿el sitio X es accesible ahora mismo?». Puse una Pi en la red de la oficina con un script de bash en cron cada minuto: hace ping a cada módem, publica 1 o 0 en Hermetry y luego crea un panel y una alerta cuando un sitio está caído.
#!/bin/bash
for h in 10.80.1.11 10.80.1.12 10.80.1.13; do
name=$(grep "$h" /home/pi/sites.txt | cut -d' ' -f2)
if ping -c 1 -W 2 $h > /dev/null; then ok=1; else ok=0; fi
mosquitto_pub -h "$BROKER" -p 8883 --capath /etc/ssl/certs -u "$TOKEN" -q 1
-t v1/telemetry -m '{"'$name'.up": $ok}'
done
Al ejecutarlo a mano no imprime nada (sin errores). En Hermetry el dispositivo no tiene claves pump3.up, solo una clave llamada raw con texto como {"pump3.up": $ok}. ¿Qué estoy haciendo mal? Y una vez que funcione, ¿cómo consigo una alerta solo cuando un sitio esté realmente caído y no por un ping perdido? Los pings celulares se pierden mucho.
I’m a data analyst, not a network person, so be kind. We have 7 remote pump stations on cellular modems, and our ops team keeps asking «is site X reachable right now». I put a Pi on our office network with a bash script on cron every minute: ping each modem, publish 1 or 0 to Hermetry, then make a board and an alert when a site is down.
#!/bin/bash
for h in 10.80.1.11 10.80.1.12 10.80.1.13; do
name=$(grep "$h" /home/pi/sites.txt | cut -d' ' -f2)
if ping -c 1 -W 2 $h > /dev/null; then ok=1; else ok=0; fi
mosquitto_pub -h "$BROKER" -p 8883 --capath /etc/ssl/certs -u "$TOKEN" -q 1
-t v1/telemetry -m '{"'$name'.up": $ok}'
done
Running it by hand prints nothing (no errors). In Hermetry the device has no pump3.up keys at all, just a key called raw with text like {"pump3.up": $ok}. What am I doing wrong? And once it works, how do I get an alert only when a site is really down and not on one lost ping? Cellular pings drop a lot.
Traducido del English por IA ·
Tus comillas simples impiden que $ok se expanda. Ese texto literal no es JSON válido, así que se guarda como raw.
Your single quotes stop $ok from expanding. That literal text isn’t valid JSON, so it gets stored as raw.
Traducido del English por IA ·
¿Cron lo está ejecutando siquiera? En nuestro caso nunca se ejecutó porque el script no era ejecutable
Is cron running it at all? Ours never ran because the script wasn’t executable
Traducido del English por IA ·
Se ejecuta, el valor raw se actualiza cada minuto. Así que es el tema de las comillas. Siempre me lío con las comillas de bash.
It runs, raw updates every minute. So it’s the quoting. I always get confused by bash quotes.
Traducido del English por IA ·
Aisha tiene razón. Hermetry guarda un cuerpo que no es JSON como una única clave raw, por eso ves el texto de tu plantilla. Construye el JSON con printf y envía todos los sitios en un solo mensaje, es más barato y ordenado:
#!/bin/bash
json="{"
while read -r ip name; do
if ping -c 3 -W 2 "$ip" > /dev/null 2>&1; then ok=1; else ok=0; fi
json+=$(printf '"%s.up":%d,' "$name" "$ok")
done < /home/pi/sites.txt
json="${json%,}}"
mosquitto_pub -h "$BROKER" -p 8883 --capath /etc/ssl/certs -u "$TOKEN" -q 1
-t v1/telemetry -m "$json"
Tres pings, no uno: se considera activo si cualquiera de ellos responde.
Para la alerta, una regla de alarma en el perfil por clave de sitio con un debounce por conteo, de modo que necesite varias lecturas malas seguidas antes de activarse y varias buenas para desactivarse:
{ "type": "pump3_unreachable",
"title": "Pump 3 modem not answering",
"severities": [ { "severity": "MAJOR", "condition": { "key": "pump3.up", "op": "==", "value": 0 } } ],
"debounce": { "mode": "count", "raise": 5, "clear": 2 },
"enabled": true }
Cinco minutos de pings fallidos antes de que alguien se entere. Añade también una regla Device offline para la Pi, si no, una Pi caída parece que «todo va bien». Opciones de debounce: Debounce, hysteresis and dampening.
Aisha has it. Hermetry stores a body that isn’t JSON as a single raw key, which is why you see your template text. Build the JSON with printf, and send all sites in one message, cheaper and tidier:
#!/bin/bash
json="{"
while read -r ip name; do
if ping -c 3 -W 2 "$ip" > /dev/null 2>&1; then ok=1; else ok=0; fi
json+=$(printf '"%s.up":%d,' "$name" "$ok")
done < /home/pi/sites.txt
json="${json%,}}"
mosquitto_pub -h "$BROKER" -p 8883 --capath /etc/ssl/certs -u "$TOKEN" -q 1
-t v1/telemetry -m "$json"
Three pings, not one: counts as up if any one comes back.
For the alert, an alarm rule on the profile per site key with a count debounce, so it needs several bad readings in a row before it opens and several good ones to clear:
{ "type": "pump3_unreachable",
"title": "Pump 3 modem not answering",
"severities": [ { "severity": "MAJOR", "condition": { "key": "pump3.up", "op": "==", "value": 0 } } ],
"debounce": { "mode": "count", "raise": 5, "clear": 2 },
"enabled": true }
Five minutes of failed pings before anyone hears about it. Add a Device offline rule for the Pi too, otherwise a dead Pi looks like «everything fine». Debounce options: Debounce, hysteresis and dampening.
Traducido del English por IA ·
Siete reglas casi idénticas son mucho que mantener sincronizado. Consideraría hacer que cada sitio sea su propio dispositivo hijo de la Pi (topics de gateway) para que una sola regla sobre up los cubra a todos. Para 7, cualquiera de las dos opciones sirve.
Seven near-identical rules is a lot to keep in sync. I’d consider making each site its own child device of the Pi (gateway topics) so one rule on up covers all of them. Fine either way for 7.
Traducido del English por IA ·
¡Arreglado! La versión con printf funciona, aparecen las siete claves .up y raw dejó de actualizarse. Al final seguí la idea de Ciaran porque el equipo de operaciones añadirá más sitios, así que ahora cada sitio es un hijo con una sola clave up y una regla. La Pump 6 tuvo una avería real anoche y la alarma se abrió tras 5 minutes, como debe ser.
Fixed! printf version works, all seven .up keys show up and raw stopped updating. Went with Ciaran’s idea in the end because ops will add more sites, so now each site is a child with a single up key and one rule. Pump 6 had a real outage last night and the alarm opened after 5 minutes like it should.
- Debes estar registrado para responder a este debate.
Únete a la conversación
Inicia sesión para preguntar y responder, dar me gusta a las publicaciones útiles y marcar la respuesta que resolvió tu problema. Cada aportación suma puntos y niveles.

