Saltar al contenido

Cómo registrar caídas de conexión a Internet

Ya no necesitas investigar más por todo internet ya que estás al espacio necesario, tenemos la solución que quieres recibir y sin liarte.

Solución:

puede hacer una verificación en:

cat /sys/class/net/wlan0/carrier

donde wlan0 es mi interfaz de Internet. puede utilizar cualquier interfaz que esté utilizando, como eth0, eth1, wlan0 para la conectividad a Internet. si la salida de ese comando es 1, entonces está conectado. de lo contrario, no. por lo que puede escribir un script como este:

#!/bin/bash
# Test for network conection
for interface in $(ls /sys/class/net/ | grep -v lo);
do
if [[ $(cat /sys/class/net/$interface/carrier) = 1 ]]; then ; echo "online"; fi
done

también puede usar el comando:

#hwdetect --show-net

este script también funciona bien:

#!/bin/bash

WGET="/usr/bin/wget"

$WGET -q --tries=20 --timeout=10 http://www.google.com -O   /tmp/google.idx &> /dev/null
if [ ! -s /tmp/google.idx ]
then
  echo "Not Connected..!"
else
  echo "Connected..!"
fi

Preguntarle a su sistema si cree que tiene una conexión es una medida indirecta de “¿mi ISP está descartando cosas?”. Las medidas proxy son, por definición, un modelo simplificado del sistema de interés y no conservan la información. La pregunta solo se puede responder obteniendo la información que le interesa.

ping En realidad, es una mala elección de pruebas porque es un protocolo ICMP que a menudo recibe un tratamiento especial. Si, por ejemplo, está interesado en la conectividad HTTP, algo como

curl --head http://www.example.com

mostrará si realmente puede obtener páginas. Si lo encuesta, sea cortés y use un mínimo de 60 segundos de sueño entre ellos. Una interrupción del ISP de menos de un minuto podría considerarse “no una interrupción”.

Dado su requisito relativamente simple, sí, un simple ping servirá. No es necesario que utilice Google como anfitrión de prueba. Si su ISP tiene un sitio web público, lo cual es muy probable en estos días, utilícelo en ese momento.

Aquí está un [bash] script que tenía la intención de usar con un antiguo proyecto mío en pausa. Es solo pingsa host y recopila estadísticas, que imprime a pedido en el registro del sistema. Las únicas dependencias son ping y bc. Tenga en cuenta que necesitará una versión no tan antigua de ping, es decir, un sistema consciente de las capacidades de Linux ping.

La secuencia de comandos utiliza valores de firma e intervalo predefinidos y está diseñado para ejecutarse de forma interactiva o en segundo plano, por ejemplo, en caso de que necesite algún registro; es necesario dar un comando externo. Obtendrá detección de aleteo y detección de enlace ascendente / descendente por el mismo precio ;-). Tiene ayuda incorporada en caso de que la necesite. No dude en preguntar si tiene alguna pregunta.

Lo escribí como un ejercicio manteniendo la huella de memoria lo más baja posible. Recuerdo que planeé hacerlo funcionar con dash, pero hay un bashismo del que no pude deshacerme hasta ahora. Con la esperanza de que le resulte útil, aquí va:

#!/bin/bash
#
#  ping.sh
#
#  Copyright 2014 VinzC <[email protected]>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
# Runs in the background ping'ing given addresses. May send
# notifications through an external routine that is given as
# an argument.
#
# Uses environment variables:
#   * LOG_FILE (log file for debug purposes, silent otherwise)
#
# Symlinked as /usr/bin/anemon-ping

VERSION=1.0.3
AUTHOR="VinzC <[email protected]>"
DATE="Jan 2014"

# Background ping, keep only relevant information from the
# response, add timestamp in seconds. For use with graphing.

# Default padding for ICMP packets
ICMP_PADDING_DEFAULT=ffeab16b00b1e2

# Default number of seconds between ICMP probes
ICMP_INTERVAL_DEFAULT=300

# Number of samples to declare a host state steady
ICMP_STEADY_THRESHOLD=3

# Number of samples in which a host is allowed to go down
# 3 times before being flagged as flapping. (Why 3? 2 is
# not enough to make it a habbit, 3 is...)
ICMP_FLAPPING_THRESHOLD=24

# Number of samples after which dupe and damaged packets
# are gone for good. Default matches 24 hours.
ICMP_NET_ERROR_THRESHOLD=288

# Host state change command. The command is called with two or
# three arguments: host name and state, plus optional arguments.
# See usage for events.
host_cmd=false

# True if results shall be written to the standard output
verbose=false

# State variables
host_state=1            # Bit0: 1=up, 0=down
                        # Bit1: 1=flapping, 0=normal
host_unavail_state=0    # State counters
host_flap_state=0
host_warning_state=0

rtt_min=                # Ping statistics
rtt_max=
rtt_avg=

icmp_seq=0              # Number of requests
icmp_lost=0             # Count of losses

icmp_dupes=             # Network errors (counters)
icmp_damaged=

usage()

    cat <[email protected]!#^G temporary variable to check getopt return code!
    args="$(getopt 
        -o i:I:p:P:s:W:hv 
        -l host-command:,flapping-threshold:,error-threshold 
        -- "[email protected]")" && eval set -- "$args" && unset args || return $?

    # Now check the remaining arguments
    while [ -n "$1" ]; do
        [ "$1" = "--" ] || case $1 in

            --host-command)
                host_cmd=$2; shift;;

            --flapping-threshold)
                ICMP_FLAPPING_THRESHOLD=$2; shift;;

            --error-threshold)
                ICMP_NET_ERROR_THRESHOLD=$2; shift;;

            -i)
                ICMP_INTERVAL=$2; shift;;
            -p)
                ICMP_PADDING=$2; shift;;
            -P)
                ICMP_PADDING=$(printf "$2" | od -A n -t x1 | 
                    sed -r -e 's:s+::g' -e 's:.::33g'); shift;;
            -I)
                ICMP_IFACE=$2; shift;;
            -s)
                ICMP_PKTSIZE=$2; shift;;
            -W)
                ICMP_TIMEOUT=$2; shift;;
            -v)
                verbose=true;;
            -h)
                help;;
            *)
                ICMP_HOST="$1";;
        esac; shift
    done
    [ -n "$ICMP_HOST" ] || usage 1>&2
}

logger()
 
        /usr/bin/logger -t "$0##*/[$$]" "[email protected]"


set_response_time()
 
        printf "%d: seq=%d, time=%sn" "$1" "$2" "$3"
    return 0


set_state_up()

    # Clear flapping state ans set (steady) up flag
    host_state=0x01

    # Call the external notification function and log host state
    $host_cmd $ICMP_HOST "up"
    logger "Host interface or host @ $ICMP_HOST is now up."


set_state_down()

    # Clear up flag only
    host_state=$(( host_state & 0xFE ))

    # Call the external notification function and log host state
    $host_cmd $ICMP_HOST "down"
    logger "Host interface or host @ $ICMP_HOST is down!"


set_state_flapping()

    # Set flapping and down flags
    host_state=2

    # Call the external notification function and log host state
    $host_cmd $ICMP_HOST "flapping"
    logger "Host interface or host @ $ICMP_HOST is unstable!"


set_host_message()

    # Reset error counter to the maximum
    host_warning_state=$ICMP_NET_ERROR_THRESHOLD

    # Call the external notification function and log host state
    $host_cmd $ICMP_HOST $1
    logger "Errors received from host interface or host @ $ICMP_HOST ($1)!"


print_stats()
 bc )
        logger "PING $ICMP_HOST: $icmp_seq packets sent, $icmp_lost lost, $icmp_losses% loss$rtt_min:+; rtt min/avg/max = $rtt_min/$rtt_avg/$rtt_max ms$icmp_dupes:+, $icmp_dupes dupes$icmp_damaged:+, $icmp_damaged bad CRC"
    fi


echo_reply()
 
    [ $host_unavail_state -ne 0 ] 

no_response()

    # Store the number of lost replies
    icmp_lost=$(( icmp_lost + 1 ))

    # FLAPPING DETECTION
    # ------------------
    # Increment flapping state using a discrete low-pass formula
    # to prevent excessive values. Handle flapping only if host
    # has just come down, don't wait for a steady "down" state.
    [ $host_unavail_state -eq 0 ] && 
    [ $(( host_flap_state=(3*host_flap_state + 7*ICMP_FLAPPING_THRESHOLD) / 8 )) -gt $ICMP_FLAPPING_THRESHOLD ] && 
        set_state_flapping

    # Increment host state until it reaches the threshold, which
    # marks the steady "down" state. Only then call the external
    # command to allow notifying the host is "down". Just don't
    # call the command more than once if the host is still down
    # by the next time.
    [ $host_unavail_state -lt $ICMP_STEADY_THRESHOLD ] && 
    [ $(( host_unavail_state=host_unavail_state + 1 )) -eq $ICMP_STEADY_THRESHOLD ] && 
    [ $(( host_state & 0x03 )) -eq 1 ] && 
        set_state_down


# Parse command-line arguments and set globals
parse_args "[email protected]" || exit $?

# Redirect stderr to LOG_FILE if defined
[ -z "$LOG_FILE" ] || exec 2>$LOG_FILE

# Print PING statistics upon receiving SIGUSR1
trap print_stats HUP

# Send even "stop" upon terminating
trap "printf 'n'; $host_cmd $ICMP_HOST stop; print_stats" INT QUIT TERM ABRT


# Notify monitoring starts
$host_cmd $ICMP_HOST "start"

# 1. filter out lines keeping only those that include response
#    times and those about non responding hosts.
# 2. Stick units to response times and keep only the multiplier
#    if it's different from "m"
# 3. Keep only the integer part of the timestamp, erase garbage
#    before the relevant information (var=value)
# 4. Warn about damaged and duplicate packets
#
# Make sure sed does NOT buffer output (hence -u)
while read R; do
    echo_reply $R || no_response

    # Decrement other state variables until it reaches zero
    [ $host_flap_state -eq 0 ] || 
        host_flap_state=$(( host_flap_state - 1 ))

    [ $host_warning_state -eq 0 ] || 
        host_warning_state=$(( host_warning_state - 1 ))

# Downside: need bash for process redirection, which is needed
# to access state variables outside the while/read loop...
done < <(LC_ALL=POSIX /bin/ping -OD 
    $ICMP_IFACE:+-I $ICMP_IFACE 
    $ICMP_TIMEOUT:+-W $ICMP_TIMEOUT 
    $ICMP_PKTSIZE:+-s $ICMP_PKTSIZE 
    -i $ICMP_INTERVAL:-$ICMP_INTERVAL_DEFAULT 
    -p $ICMP_PADDING:-$ICMP_PADDING_DEFAULT $ICMP_HOST |
sed -rnu 
    -e '/no answer|[0-9]+ bytes from/!d' 
    -e '[email protected](time=[0-9.]+)s+m?(w*)[email protected]1[email protected]' 
    -e '[email protected](DUP!)@msg="dupes"@g' 
    -e '[email protected](BAD CHECKSUM!)@msg="damaged"@g' 
    -e '[email protected][(w+).w+][a-zA-Z0-9():. -]+[email protected]1 @gp')

Al final de la artículo puedes encontrar las observaciones de otros gestores de proyectos, tú igualmente puedes dejar el tuyo si te apetece.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *