如何监视网络并执行处理?

Bash

1 前言

一个问题,一篇文章,一出故事。
笔者今天遇到家里的服务器网络故障,由于在上班,无法及时修复。
下班后检查不知为何网卡地址丢失(可能与刚进行系统升级有关),检查系统日志亦无所获,但通过重启网络服务可恢复网络。
于是,笔者想到暂时先写一个脚本监视网络状态并自动处理,容后再慢慢查找原因。

2 最佳实践

2.1 创建脚本目录

mkdir ~/scripts

2.2 创建脚本

vim ~/scripts/monitorNetwork.sh

加入如下配置,

#!/bin/bash

sleepTime="1"
errCountThreshold="10"
monitorLogs="/var/log/monitorNetwork.log"
pidFile="/run/monitorNetwork.pid"

monitorNetwork() {
        errCount=0
        runSleepTime="$sleepTime"
        while true; do
                sleep "$runSleepTime"
                ping -c 1 _gateway > /dev/null 2>&1
                if [ "$?" -eq "0" ]; then
                        errCount=0
                        runSleepTime="$sleepTime"
                fi
                ((errCount++))
                if [ "$errCount" -ge "$errCountThreshold" ]; then
                        echo `date +"%Y-%m-%d %H:%M:%S"`" Failed to ping the gateway for ${errCount} consecutive times." >> $monitorLogs
                        #systemctl restart NetworkManager network
                        systemctl restart NetworkManager.service networking.service
                        runSleepTime="180"
                fi
        done
}


if [ -f "$pidFile" ]; then
        pid=$(cat "$pidFile")
        if kill -0 $pid 2>/dev/null; then
                echo "The script is already running,PID: $pid"
                exit 1
        fi
        rm -f "$pidFile"
fi

echo $$ > "$pidFile"
trap "rm -f $pidFile; exit" SIGINT SIGTERM
monitorNetwork

2.3 设置脚本触发

crontab -e

加入如下设置,

*/30 * * * * bash ~/scripts/monitorNetwork.sh
没有评论

发表回复

Bash
如何用Tigase监控Elasticsearch集群?

1 前言 一个问题,一篇文章,一出故事。 笔者生产中有一套Elasticsearch集群,笔者为了能 …

Bash
如何用Base Shell获取ES集群状态?

1 前言 一个问题,一篇文章,一出故事。 笔者想要通过Base Shell获取Elasticsear …

Bash
如何熟悉grep命令?

截取括弧“()”中的字符串, echo “This is a test (sample string …