shell脚本--查看应用的cpu 和 内存使用率 并把最新告警内容显示出来
#/bin/bash
#awk NR==2'{print $4}':awk
处理前一步结果,NR==2
表示取第 2 行,print $4
提取该行第 4 列内容(一般是进程 PID),最终把 PID 赋值给变量 ics_pid
。
ics_pid=ps -efl |grep app |grep -v grep |awk NR==2'{print $4}'
#| awk '{print $9}':提取每行第 9 列(top 中第 9 列默认是 CPU 使用率)。awk NR==1'{print $1}':在 CPU 使用率结果里,取第 1 行数据,赋值给 cpu_usage
(理论上多次采集结果一致,取首行简化)。
cpu_usage=top -n 3 |grep $ics_pid |awk '{print $9}'|awk NR==1'{print $1}'
mem_usage=top -n 3 |grep $ics_pid |awk '{print $10}'|awk NR==1'{print $1}'
#date +"%Y-%m-%d %H:%M:%S"
:调用系统 date
命令,按年-月-日 时:分:秒
格式输出当前时间。
date1=date +"%Y-%m-%d %H:%M:%S"
date=date +"%Y%m%d"
#重定向cpu 使用率到固定文件中
echo "$date app cpu_usage $cpu_usage" > /xxx/$date1.log
#追加内存使用到文件中
echo "$date app mem usage $mem_usage" >> /xxx/$date1.log
#查看是否有告警日志
num=ls /xxx/log |grep vquar.log|wc -l
#大于等于
if [ $num -ge 1 ];then
#有告警日志
echo "##### has gaojing file######" >> /xxx/$date1.log
#把告警日志最后100行追加到固定文件中
tail -100 /xxx/vquar.log >> /xxx/$date1.log
fi
cat /xxx/$date1.log