#!/bin/bash
# -------------------------------------------------------------------------------
# FileName:    networkchecking
# Revision:    2.0
# Date:        2017/09/14
# Author:      XAD
# Email:       [email protected]
# Website:     http://onenice.blog.51cto.com/
# Description: check network and sendmail to XAD , wirte executing log
# Notes:       ~
# -------------------------------------------------------------------------------
# Copyright:   2017(c)XAD
# License:     GPL

DOMAIN1=www.baidu.com
DOMAIN2=www.google.com
DATE=`date "+%F %H:%M:%S"`
HOST=`hostname`
IPADDRESS=`ifconfig eth0| grep "inet addr:" | awk -F[:" "]+ '{print $4}'`

##打印成功日志##
log_info()
{
    if [ ! -x /var/log/$0 ];then
        mkdir /var/log/$0
    fi
        echo "$DATE $HOST $IPADDRESS $USER execute  $0 >> $1" >> /var/log/$0/success.log
}

##打印错误日志##
log_error()
{
    if [ ! -x /var/log/$0 ];then
        mkdir /var/log/$0
    fi
        echo "$DATE $HOST $IPADDRESS $USER execute $0 >> $1" >>/var/log/$0/error.log
}

##检测网络是否通畅##
check_network()
{
    ping -c 2 $DOMAIN1 > /dev/null
    pingstatus1=$?
    echo -n $pingstatus1 > /tmp/netwok-status
    if [ $pingstatus1 -eq 0 ];then
        log_info "Network to $DOMAIN1 is ok"
    else
        log_error "Network to $DOMAIN1 is error"
    fi
    
    ping -c 2 $DOMAIN2 > /dev/null
    pingstatus2=$?
    echo -n $pingstatus2 >> /tmp/netwok-status
    if [ $pingstatus2 -eq 0 ];then
        log_info "Network to $DOMAIN2 is ok"
    else
        log_error "Network to $DOMAIN2 is error"
    fi
}

##发送警报邮件并输出发送日志##
sendmail()
{
    STATUS=`cat /tmp/netwok-status`
    if [ "$STATUS" -eq 11 ]; then
        echo "TIME:$DATE HOSTNAME:$HOST IP:$IPADDRESS Network is normal! " | mail -s "Please check your network now!" [email protected]
        if [ $? -eq 0 ];then
            echo "$DATE $HOST $IPADDRESS $USER >> sendmail is ok !" >> /var/log/$0/sendmail.log
        else
            echo "$DATE $HOST $IPADDRESS $USER >> sendmail is error !" >> /var/log/$0/sendmail.log
        fi
fi
}

check_network
sendmail