网络流量监控
需求
实时掌握网卡的流量,掌握带宽使用情况
思路
1、获取网卡当前流入流出总量
2、睡眠一秒
3、获得网卡当前流入流出总量
4、相减计算一秒的总流量
代码实现
#!/bin/bash
#
#Author: www.zutuanxue.com
#Created Time:
#Release:
#Description: 网卡流量监控
#脚本用法
#判断用户是否传参
if [ -z "$1"] || [ "$1" == "--help" ];then
cat << EOF
$0 网卡名称
--help 打印帮助菜单
EOF
fi
#如果用户没有传参,则退出脚本
[ $# -lt 1 ]&&exit 1
#第一次取值
#1、获得当前网卡流量 初始化值
NIC_RX=`ifconfig $1|grep "RX packets"|tr -s " "|cut -d " " -f6`
NIC_TX=`ifconfig $1|grep "TX packets"|tr -s " "|cut -d " " -f6`
#休息一秒开始循环
sleep 1
#循环开始监控网卡流量 监控频率 1s
while :
do
#2、监控当前网络的流量,第二次取值
NIC_RX_1=`ifconfig $1|grep "RX packets"|tr -s " "|cut -d " " -f6`
NIC_TX_1=`ifconfig $1|grep "TX packets"|tr -s " "|cut -d " " -f6`
#3、制作输出
#3.1、清屏输出下文
clear
echo -e "\t$1 网卡流量监控"
echo "----------------------------------------"
echo -e "网卡: $1\n"
#3.2、运算得出结论
echo -e "发送:\t$((NIC_TX_1-NIC_TX))B/s\t接收:\t$((NIC_RX_1-NIC_RX))B/s"
#重新赋值网卡初始化流入流出变量
NIC_RX=$NIC_RX_1
NIC_TX=$NIC_TX_1
#休眠1秒,进入下一次循环
sleep 1
done
接口监控
需求
URL监控脚本,对某个URL进行监控,返回值为200则代表成功访问。
思路
1、使用curl访问一次URL,并将输出保存
2、访问输出文件,获取返回值
3、判断返回值是否和初始预设的返回值相等,并对应输出
#!/bin/bash
#
#Author:
#Created Time:
#Release:
#Description: URL监控脚本
#监控阈值可以是: 状态码、页面字符串、页面所有内容
#本例以状态码为例
#variables
init_url_status=200
# 临时文件
temp_file=`mktemp /tmp/check_url.txt`
#help
if [ -z "$1" ]||[ "$1" == "--help" ];then
echo "$0 url"
echo "--help: 打印该帮助"
fi
#如果用户没有传参则退出
[ $# -lt 1 ]&&exit 1
#main
#1、使用curl命令访问一次URL
#1.1 判断脚本依赖命令是否存在
[ ! -x /usr/bin/curl ]&&echo "curl: not found command"&&exit 1
#1.2 访问一次URL
curl -I $1 &> $temp_file
#2、从输出中截取状态码
url_status=`grep "HTTP/1.1" $temp_file|cut -d " " -f2`
#2.1如果取值失败直接报错(测试发现当无法访问URL时会在第三步中报比较错误,所以这里取不到值就不往下走了)
[ -z "$url_status" ]&&echo -e "\033[31mstatus:NULL\033[0m"&&exit 1
#3、判断状态码是否和预设的一致
#3.1 一致 输出绿色字体 "status:200"
#3.2 不一致 输出红色字体 "status:XXX"
if [ $init_url_status -eq $url_status ];then
echo -e "\033[32mstatus:$url_status\033[0m"
else
echo -e "\033[31mstatus:$url_status\033[0m"
fi
#4、删除临时文件
rm -f $temp_file