简体   繁体   中英

Bash script to check the network status - linux

I wrote a bash script:

RRR=$(ifconfig eth0 | grep 'inet addr:' | cut -d: -f2)
if [[ ${RRR} == null ]]; then
`zenity --error --text "NO NETWORK"`
else
`zenity --error --text "NETWORK IS ON"`
fi

but its not working fine - when i cut off the network the error message doesn't show on

any suggestions?

thanks' ahead

I think ping is help you as alternative But you already solved it interesting to popup message window with network status.

ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && echo "NETWORK IS ON" || echo "NO NETWORK"

or

 ROUTER_IP="your router ip"
    ( ! ping -c1 $ROUTER_IP >/dev/null 2>&1 ) && service network restart >/dev/null 2>&1

try this:

find /proc/irq/ -name \*eth0\* | fgrep -q eth0 && echo up || echo down

if the interface is loaded it will apear

root@stormtrooper:/proc# ifconfig eth0 down
root@stormtrooper:/proc# find /proc/irq/ -name \*eth0\* | fgrep -q eth0 && echo up || echo down
down
root@stormtrooper:/proc# ifconfig eth0 up
root@stormtrooper:/proc# find /proc/irq/ -name \*eth0\* | fgrep -q eth0 && echo up || echo down
up

I don't know if it will refear to linkstate... but use /proc is always faster

You can use ping command to analyze connection quality. I use this function to test current interface in linux. It's ping destination address 10 times and return 0 - if succeed, 1- otherwise. It just one of possibility.

param1 - interface name (eth0, tun0...); param2 - ping destination

ping_interface() {
    # Max value of losted packages in %
    MAX_PACKETS_LOST=80
    PACKETS_COUNT=10
    PACKETS_LOST=$(ping -c $PACKETS_COUNT -I $1 $2 |grep % | awk '{print $7}')
    if ! [ -n "$PACKETS_LOST" ] || [ "$PACKETS_LOST" == "100%" ];
    then
        # 100% failed
        return 1
    else
        if [ "${PACKETS_LOST}" == "0%" ];
        then
            #ping is OK
            return 0
        else
            # Real value of losted packets between 0 and 100%
            REAL_PACKETS_LOST=$(echo $PACKETS_LOST | sed 's/.$//')
            if [[ ${REAL_PACKETS_LOST} -gt ${MAX_PACKETS_LOST} ]];
            then
                echo "Failed. Lost more then limit"
                return 1
            else
                echo "Connection is ok."
                return 0
            fi
        fi
    fi
}

ping_interface eth0 8.8.8.8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM