一:监控目的
掌握系统进程对系统资源的使用情况,掌握及其的动态
二:监控方法
(1)监控命令
ps:静态,显示上一秒的状态
top:动态
(2)监控方法
通过对任务管理器中的进程对内存或者CPU的使用情况进行整合,排序得出结论
三:监控实现代码及测试结果
#统计系统中前十名使用内存最多的进程
memory () {
#1、收集任务管理器信息
temp_file=`mktemp memory.XXX`
top -b -n1 > $temp_file #top -n1 打印一次,-b打印所有内容
#2、按进程统计内存使用率
tail -n +8 $temp_file | awk '{array[$NF]+=$6}END{for (i in array) print array[i],i}' | sort -k 1 -n -r | head -10
#sort -k 1 -n -r 根据第1列按数字排序,倒序
rm -f $temp_file
echo
}
#统计系统中前十名使用CPU最多的进程
CPU () {
#1、收集任务管理器信息
temp_file=`mktemp memory.XXX`
top -b -n1 > $temp_file
#2、按进程统计CPU使用率
tail -n +8 $temp_file | awk '{array[$NF]+=$9}END{for (i in array) print array[i],i}' | sort -k 1 -n -r | head -10
rm -f $temp_file
}
echo memory
memory
echo CPU
CPU
[root@localhost opt]# vi 34test.sh
[root@localhost opt]# sh 34test.sh
memory
117228 gnome-shell
88464 mysqld
28752 firewalld
19684 gnome-settings-
18624 tuned
16872 X
16864 libvirtd
12412 polkitd
9760 gnome-session-b
9428 abrt-watch-log
CPU
0 xprtiod
0 xfs-reclaim/sda
0 xfs-reclaim/dm-
0 xfs_mru_cache
0 xfs-log/sda1
0 xfs-log/dm-0
0 xfs-eofblocks/s
0 xfs-eofblocks/d
0 xfs-data/sda1
0 xfs-data/dm-0
补充:
top -n1 打印一次
tail -n 10 XXX 打印文件XXX中最后10行(tail表示结尾的意思)
tail -n +8 XXX 打印文件XXX中从第8行开始下面的内容
lsof -i :80(查看80端口谁在用)