50.检测网卡状态脚本

思路:sar -n DEV 1 10监测网卡进出流量,若是进出流量都为0则网卡异常
#!/bin/bash
LANG=en#定义语言
if [ $# -ne 1 ] || ! ip addr show $1 &>/dev/null;then 
#输入参数是否为1, ! ip addr show判断网卡是否存在
        echo "Please input correct network card." 
        exit
fi
echo "Checking..."#输出检测信息
sar_in=`sar -n DEV 1 10 |grep " $1 "|grep -i average:|awk '{print $5}'`
#进网卡流量
sar_out=`sar -n DEV 1 10 |grep " $1 "|grep -i average:|awk '{print $6}'`
#出网卡流量
if [ "$sar_in" == "0.00" ] && [ "$sar_out" == "0.00" ];then
#判断进出网卡流量是否都为0
        while true#while 循环执行判断是否重启网卡
        do
             read -p "The network card is down,do you want to restart it?(y or n) " net
             case $net in
             y)
             echo "Restarting..."#输出重启信息
             ifdown $1 2>/dev/null
             ifup $1 2>/dev/null
             if [ $? -eq 0 ];then#判断重启是否成功
                echo "The network card was restarted successfully!"
                break#退出循环
             else
                echo "DEV $1 failed to start!"
                break#退出循环
             fi
             ;;
             n)
             echo "Bye!"
             exit 1
             ;;
             *)
             echo "Please input y or n."
             continue#从新循环
             ;;
             esac
        done
else
        echo "The network card is in good condition!"
fi
使用 :sh dev_sar.sh eth0