查找Linux中内存和CPU使用率最高的进程
需求:创建一个定时任务,每30分钟输出该时刻(年月日分秒)系统中内存占用最大的四个进程名及进程占用内存
- 打印当前系统时间(年月日分秒)
[root@localhost /]# date "+%Y-%m-%d %H:%M:%S" 2017-08-30 09:54:08
- 打印出系统消耗内存资源最高的四个进程
[root@localhost /]# ps aux | grep -v "USER" | sort -rn -k +4 | head -4 | awk -F ' ' '{print $11,$4}' /usr/lib/vmware-vgauth/VGAuthService 0.9 /usr/sbin/vmtoolsd 0.7 /usr/lib/vmware-caf/pme/bin/ManagementAgentHost 0.5 sshd: 0.4
- 脚本如下:
#!/bin/bash date=`date "+%Y-%m-%d %H:%M:%S"` #打印消耗资源内存最高的进程名 first=`ps aux | grep -v "grep" | grep -v "USER" | sort -rn -k +4 | head -4 | awk -F ' ' '{print $11}' | sed -n 1p` Second=`ps aux | grep -v "grep" | grep -v "USER" | sort -rn -k +4 | head -4 | awk -F ' ' '{print $11}' | sed -n 2p` Third=`ps aux | grep -v "grep" | grep -v "USER" | sort -rn -k +4 | head -4 | awk -F ' ' '{print $11}' | sed -n 3p` Fourth=`ps aux | grep -v "grep" | grep -v "USER" | sort -rn -k +4 | head -4 | awk -F ' ' '{print $11}' | sed -n 4p` #打印消耗内存资源最高进程、内存使用率 one=`ps aux | grep -v "grep" | grep -v "USER" | grep "$first" | awk -F ' ' '{print $4}'` two=`ps aux | grep -v "grep" | grep -v "USER" | grep "$Second" | awk -F ' ' '{print $4}'` three=`ps aux | grep -v "grep" | grep -v "USER" | grep "$Third" | awk -F ' ' '{print $4}'` four=`ps aux | grep -v "grep" | grep -v "USER" | grep "$Fourth" | awk -F ' ' '{print $4}'` #使用echo打印结果 echo "$date $first $one" echo "$date $Second $two" echo "$date $Third $three" echo "$date $Fourth $four"
- 每30分钟执行一次脚本
[root@localhost /]# crontab -e crontab: installing new crontab [root@localhost /]# crontab -l */30 * * * * /bin/bash /mem.sh >>/mem.log
- 执行mem.sh脚本输入结果如下:
[root@localhost /]# ./mem.sh 2017-08-30 10:27:30 /usr/lib/vmware-vgauth/VGAuthService 0.9 2017-08-30 10:27:30 /usr/sbin/vmtoolsd 0.7 2017-08-30 10:27:30 /usr/lib/vmware-caf/pme/bin/ManagementAgentHost 0.5 2017-08-30 10:27:30 sshd: 0.4