Linux下用脚本写监控代理程序
吴旻
泰岩网络工作室
因工作需要,我需要监控几台服务器的程序状态,SNMP(简单网络管理协议)可以用,但并不能满足我的要求,而且并不简单。我希望实时得到诸如进程的信息、CPU使用、内存使用、网络流量、网络端口、磁盘信息使用等众多参数。
我很快写好了监控服务端和客户端程序,但对代理端程序却一时难以确定技术方案。用任何一种语言获得这些参数都需要深入了解操作系统,好在Linux下有丰富的命令程序,估计可以帮我尽快解决问题。
一、各种数据的收集。
这个难度不太大,因为Linux下命令丰富,所以可以很快搞定。比如,我想知道当前有没有程序使用网络端口8888,用如下命令即可解决:
netstat -ant | grep :8888
或者类似我下面的,将得到的数据更具体一些:
netstat -ant | grep 192.168.10.22:8888 | awk '{print $5,$4}'
二、格式化保存
网络数据一般都是有固定格式,甚至包括校验值等功能。我的这个没那么复杂,但也同样要有包标识符、包消息ID、包消息体长度等值。我是这样实现的: MonitorMsg="/xff/xff/xff/xff" # msg_flag = 0xFFFFFFFF MonitorMsg=$MonitorMsg"/x01/x00/x00/x00" # msg_id = 1
MonitorMsg=$MonitorMsg"/x44/x00/x00/x00" # msg_len = 68 Bytes
消息体的具体内容就完全是个性化数据了,比如,我想加入当前操作系统时间:
timeNow=`date +%H%M%S`
MonitorMsg=$MonitorMsg$timeNow"/x00/x00"
因为时间是HH:MM:SS,为了内存对齐,后面又补了2字节的0x00。
再下面要做的就是将这些数据保存到文件中。echo命令完成了这一工作:
echo -ne $MonitorMsg >> /usr/montor.dat
使用参数 –ne 是因为默认情况下echo会自动加上回车,从而导致数据对不齐。
三、将保存后的数据发送到指定服务器。
这个命令组合超级简单,利用了tail和nc:
tail -f /usr/montor.dat | nc 192.168.1.228 6666
192.168.1.228即监控服务器所以的地址,端口号为6666。
四、一个完整的示例
这个示例由4个脚本组成。其中比较麻烦的是停止功能,因为在这里tail和nc原则上是不会自己退出来的。
1、数据收集
|
DATE=`date +%Y%m%d`
MsgLogPath=/opt/develop/monitor_station/ MsgLogFileName=Monitor.dat MsgLogFile=$MsgLogPath$MsgLogFileName
if [ -f $MsgLogFile ] ; then mv $MsgLogFile $MsgLogPath$DATE"_"$MsgLogFileName".bak" fi
timeNow=`date +%k%M%S` timeEnd=180000
while [[ $timeNow -le $timeEnd ]] do # echo $timeNow MonitorMsg="/xff/xff/xff/xff" # flag MonitorMsg=$MonitorMsg"/x01/x00/x00/x00" # id MonitorMsg=$MonitorMsg"/x44/x00/x00/x00" # len
MonitorMsg=$MonitorMsg"/x0e/x00/x00/x00" # station id = 14 MonitorMsg=$MonitorMsg$timeNow"/x00/x00" # msg body
NetStatMsg=`netstat -ant | grep 192.168.10.22:8888 | awk '{print $5,$4}'` MonitorMsg=$MonitorMsg$NetStatMsg
msg_len=${#NetStatMsg} zero_len=`expr 56 - $msg_len`
index=1 while [[ $index -le $zero_len ]] do MonitorMsg=$MonitorMsg"/x00" let index=$index+1 done
echo -ne $MonitorMsg >> $MsgLogFile
sleep 3 timeNow=`date +%k%M%S` done |
2、数据发送
|
tail -f /opt/develop/monitor_station/Monitor.dat | nc 192.168.1.228 6666 |
3、启动程序
|
nohup /opt/develop/monitor_station/rec_mon_to_file.sh > /opt/develop/monitor_station/rec_mon_to_file.log 2>&1 & sleep 5 nohup /opt/develop/monitor_station/send_mon_file.sh > /opt/develop/monitor_station/send_mon_file.log 2>&1 &
|
4、停止程序
|
ps -ef | grep -w "192.168.1.228" | awk '{print $2, $9}' | grep -w "192.168.1.228" | awk '{print $1}' | xargs kill ps -ef | grep -w "Monitor.dat" | awk '{print $2}' | xargs kill |
本文介绍了一种在Linux环境下通过Shell脚本实现服务器监控的方法,涵盖了数据收集、格式化保存及发送数据到指定服务器的过程。

3022

被折叠的 条评论
为什么被折叠?



