对于运维人员需要定时查看服务器的系统情况,有时候针对某个java进程需要查看该应用占用内存和CPU情况可以通过以下脚本实现:
#!/bin/bash
hostip=`ifconfig bond1 | grep inet | awk 'NR==1{print $2}'`
cpu_usage=$(echo "100-`top -n1 | awk 'NR==3{print $8}'`"|bc)
#cpu compute way is same
#CPU=`top -b -n1 | grep "Cpu(s)" | awk '{print $2 + $3 + $4}'`
mem_total=`free -h |awk '/Mem:/{print $2}'`
mem_used=`free -m |awk '/Mem:/{print $3+$6}'`
mem_free=`free -h |awk '/Mem:/{print $4}'`
mem_rate=$(echo "scale=2;$mem_used *100/ `free -m |awk '/Mem:/{print $2}'`"|bc)
disk_total=`df -h /opt | tail -n 1 | awk '{ print $2}'`
disk_used=`df -h /opt | tail -n 1 | awk '{ print $3}'`
disk_free=`df -h /opt | tail -n 1 | awk '{ print $4}'`
disk_rate=`df -h /opt | tail -n 1 | awk '{ print $5}'`
echo -e "\n----------------------------"
echo -e "***主机$(hostname)系统监控数据***"
echo "[$hostip]"
echo "$(date)"
echo -e "----------------------------"
echo -e "\n|=-> cpu利用率:$cpu_usage%"
echo -e "\n|=-> 内存利用率:$mem_rate% 总内存:$mem_total 已使用内存(包含buff/cache): $mem_used M 空闲内存:$mem_free"
echo -e "\n|=-> 磁盘利用率:$disk_rate 磁盘总空间:$disk_total 已使用磁盘空间: $disk_used 空闲磁盘空间:$disk_free"
pentaho_java=`top -b -n1 | grep java |grep pentaho | awk '{print $1 " " $2 " " $6 " " $10}'`
echo -e "\n|=->Pentaho application memory usage-<=| "
echo "PID User Mem usage%"
echo "$pentaho_java"
echo -e '''
----------------------
Powered by: wjz
----------------------
'''
结果:
其中上面的脚本是显示系统情况,还有另一种脚本可以写死循环,每隔几秒统计一次系统情况:
#/bin/bash
while :
do
TIME=`date +"%F_%H:%M:%S"`
CPU=`top -b -n1 | grep "Cpu(s)" | awk '{print $2 + $3 + $4}'`
TOTAL=`cat /proc/meminfo | grep MemTotal | awk '{print $2}'`
CURRENT=`cat /proc/meminfo | grep Active: | awk '{print $2}'`
FREE=`cat /proc/meminfo | grep MemFree | awk '{print $2}'`
RAM=$(echo "scale=2; $CURRENT*100 / $TOTAL" | bc)
RAM_T=$(echo "scale=2; $FREE/$TOTAL*100" | bc)
echo $TIME "CPU:" $CPU "RAM:" $RAM "%" " RAM_FREE_RATIO:" $RAM_T "%" >> check_system.txt
top -b -n1 | grep java |grep pentaho| awk -v arg1=$TIME '{print arg1, $0}' >> check_java.txt
sleep 3
done
参考文章: