监控单个进程占用cpu与内存的使用情况

时间:2022-01-27 17:07:08

#!/bin/bash
interval=1
if [ "$1" != "" ]
then
interval=$1
fi
echo "检查时间间隔(单位秒):"$interval
datetime=`date +'%Y%m%d'`
while :
do
#获取用户es占用cpu、内存、虚拟内存、物理内存、共享内存的信息
#echo `date +'%d %H:%M:%S'` %cpu: `top -n 1 -u es|tail -2|head -1|awk '{ssd=NF-4} {print $ssd}'` %mem: `top -n 1 -u es|tail -2|head -1|awk '{ssd=NF-3} {print $ssd}'` VIRT: `top -n 1 -u es|tail -2|head -1|awk '{ssd=NF-8} {print $ssd}'` RES: `top -n 1 -u es|tail -2|head -1|awk '{ssd=NF-7} {print $ssd}'` SHR: `top -n 1 -u es|tail -2|head -1|awk '{ssd=NF-6} {print $ssd}'` >> /home/es/hhs/es_user.txt
echo `date +'%d %H:%M:%S'` %cpu: `top -n 1 -p 3117|tail -2|head -1|awk '{ssd=NF-4} {print $ssd}'` %mem: `top -n 1 -p 3117|tail -2|head -1|awk '{ssd=NF-3} {print $ssd}'` VIRT: `top -n 1 -p 3117|tail -2|head -1|awk '{ssd=NF-8} {print $ssd}'` RES: `top -n 1 -p 3117|tail -2|head -1|awk '{ssd=NF-7} {print $ssd}'` SHR: `top -n 1 -p 3117|tail -2|head -1|awk '{ssd=NF-6} {print $ssd}'` >> /home/es/hhs/es_user.txt

#取系统当前时间(以追加的方式写入文件>>)
echo `date +'%d %H:%M:%S'` >> /home/es/hhs/date-time.txt

#抓取当前15分钟内cpu的占用情况(以追加的方式写入文件>>)
echo average_load: `uptime | awk '{print $NF}'` >> /home/es/hhs/average_load.txt

#抓取物理内存free值(以追加的方式写入文件>>)
echo Mem-total: `free -m | grep Mem | awk '{print $2}'`M Mem-used: `free -m | grep Mem | awk '{print $3}'`M Mem-free: `free -m | grep Mem | awk '{print $4}'`M >> /home/es/hhs/mem-free.txt

#抓取缓冲区的free值(以追加的方式写入文件>>)
echo cache-used: `free -m | grep - | awk '{print $3}'`M buffers/cache-free: `free -m | grep - | awk '{print $4}'`M >> /home/es/hhs/buffers-free.txt

#抓取Swap分区free值(以追加的方式写入文件>>)
echo Swap-total: `free -m | grep Swap | awk '{print $2}'`M Swap-used: `free -m | grep Swap | awk '{print $3}'`M Swap-free: `free -m | grep Swap | awk '{print $4}'`M >> /home/es/hhs/swap-free.txt

#逐行连接上面的时间和内存相关行数据(每次重新写入文件>)
paste /home/es/hhs/date-time.txt /home/es/hhs/average_load.txt /home/es/hhs/mem-free.txt /home/es/hhs/buffers-free.txt /home/es/hhs/swap-free.txt > /home/es/hhs/freemem.txt

sleep $interval
done