shell脚本初学与linux命令学习
shell脚本编写
由于工作原因,目前遇到一个问题,要求对程序所在服务器进行实时监控,主要监控程序的CPU利用率,程序的内存占用率。刚开始考虑用代码去写,考虑了下,还得java,再结合linux命令,写起来有点麻烦,于是想到了直接用shell编写一个定时脚本。
需求
**文件编码使用utf-8格式编码。文件产生频率为每5分钟产生一个文件,新产生的文件覆盖上一次产生的文件。文件格式为xml文件,格式样例如下: **
编写生成各字段要求的值
#!/bin/bash
#author weixg
#xml文件名
fileName="zhywgl_ywgl_waywgl.xml"
#系统程序名(进程名)
procName="FlowServer"
#版本号
procVersion="1.0"
#最近启用时间
procStartTime=`ps -eo lstart,command| grep -v 'grep'| grep -w $procName | awk '{print($1" "$2" "$3" "$4" "$5);}'`
#程序接收流量速率
inputRate="-1"
#程序输出流量速率
outputRate="-1"
#程序接收日志量大小
inputLog="-1"
#程序输出日志量大小
outputLog="-1"
#统计周期,以分钟为单位
duration="5"
#提取本服务器的ip地址信息
IP=`/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"`
#服务器用户默认root
psUser=root
#查看进程是否存在
pid=`ps -ef | grep -w $procName | grep -v 'grep' | awk '{print $2;}'`
if [ "$pid" != "" ]; then
ProcAlive=1
else
ProcAlive=0
fi
#cpu使用率
ProcCpu=`ps aux |grep -w $procName | grep -v 'grep'| awk '{print($3);}'`
#程序内存使用率
ProcMem=`ps aux |grep -w $procName | grep -v 'grep'| awk '{print($4);}'`
#时间戳
Timestamp=`date +%s`
echo "fileName is $fileName"
echo "procName is $procName"
echo "procVersion is $procVersion"
echo "inputRate is $inputRate"
echo "outputRate is $outputRate"
echo "inputLog is $inputLog"
echo "outputLog is $outputLog"
echo "duration is $duration"
echo "pid is $pid"
echo "ProcAlive is $ProcAlive"
echo "ProcCpu is $ProcCpu"
echo "ProcMem is $ProcMem"
echo "IP is $IP"
echo "procStartTime is $procStartTime"
echo "Timestamp is $Timestamp"
提取本服务器的ip地址信息
IP=/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"
分析下这个命令:
/sbin/ifconfig -a 查询本机ip
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.16.0.3 netmask 255.255.240.0 broadcast 172.16.15.255
inet6 fe80::5054:ff:fe68:1c8a prefixlen 64 scopeid 0x20<link>
ether 52:54:00:68:1c:8a txqueuelen 1000 (Ethernet)
RX packets 13295352 bytes 3943242853 (3.6 GiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 12367502 bytes 2298562223 (2.1