為了方便查看 CentOS 主機上每位使用者的 CPU 與記憶體佔用比例,我寫了一支腳本 viewUsage.sh。它的作法是先用 ps aux 取出所有行程,依使用者名彙總 %CPU 與 %MEM,再排序輸出,超過 10% 的列會以紅字標示。
#!/bin/bash
#
# view the cpu and memory consumption of each user at the current time.
# chenqy 20101126 v0.9
# chenqy 20110115 v1.0 : added the sort option: --reverse --mem --cpu
function viewconsumption {
ps aux | grep -v 'PID' | sed 's/[ ][ ]*/ /g' | cut -d " " -f1-4 | sort | awk '
BEGIN {
userid = "None"
cpuUsage = 0
memUsage = 0
}
{
if (userid == $1) {
cpuUsage += $3
memUsage += $4
} else {
if (userid != "None") {
printf("%s %4.1f %4.1f\n", userid, cpuUsage, memUsage)
}
userid = $1
cpuUsage = $3
memUsage = $4
}
}'
}
function printResult {
awk '
BEGIN {
postcolor = "\033[0;39m"
}
{
userid = $1
cpuUsage = $2
memUsage = $3
if (cpuUsage >= 10 || memUsage >= 10) {
precolor = "\033[0;31m" # red color
}
printf("%s%s \033[12G%4.1f \033[20G%4.1f%s\n", precolor, userid, cpuUsage, memUsage, postcolor)
precolor = "\033[0;39m"
}'
}
echo -e "USER \033[12G%CPU \033[20G%MEM"
echo "--------- ------ -----"
if [ "$1" == "--mem" ]; then
key="-k 3 -n"
elif [ "$1" == "--cpu" ]; then
key="-k 2 -n"
fi
if [ "$1" == "--reverse" -o "$2" == "--reverse" ]; then
reverse="-r"
fi
viewconsumption | sed 's/[ ][ ]*/ /g' | sort $key $reverse | printResult
以下輸出均為 aix.unix-center.net 上的實際執行結果。
1. 不帶參數直接執行,預設依使用者名稱升冪排序,CPU 或 MEM 超過 10% 時以紅字顯示(提示:大寫字母開頭會排在小寫前面):
tsingyee@aix bin# ./viewUsage.sh USER %CPU %MEM --------- ------ ----- Michelle 48.2 0.0 <= 此行為紅字 bookses 0.0 0.0 centos1 0.0 0.0 coolryx 0.0 0.0 daemon 0.0 0.0 root 14.1 2.0 <= 此行為紅字 tsingyee 0.0 0.0 zte_zxr1 0.0 0.0
其餘參數:--cpu 改以 CPU 佔用排序,--mem 改以記憶體佔用排序,加上 --reverse 則改為遞減,例如 ./viewUsage.sh --mem --reverse 就是列出吃記憶體最多的使用者。