需求:建立一個定時任務,每30分鐘輸出該時刻(年月日分秒)系統中內存佔用最大的四個進程名及進程佔用內存
python
打印當前系統時間(年月日分秒)bash
[root@localhost /]# date "+%Y-%m-%d %H:%M:%S" 2017-08-30 09:54:08
打印出系統消耗內存資源最高的四個進程ssh
[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
腳本以下:ide
#!/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分鐘執行一次腳本three
[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