我需要监控两台服务器(Ubuntu 和 CentOS)的用户的 CPU 使用情况。例如:
user1 5%
user2 10%
...
有类似的工具top
或者htop
可以做到这一点吗?
答案1
这是一个打印的脚本全部的每个用户的CPU使用率当前登录,显示PerUserCPU.sh:
own=$(id -nu)
cpus=$(lscpu | grep "^CPU(s):" | awk '{print $2}')
for user in $(who | awk '{print $1}' | sort -u)
do
# print other user's CPU usage in parallel but skip own one because
# spawning many processes will increase our CPU usage significantly
if [ "$user" = "$own" ]; then continue; fi
(top -b -n 1 -u "$user" | awk -v user=$user -v CPUS=$cpus 'NR>7 { sum += $9; } END { print user, sum, sum/CPUS; }') &
# don't spawn too many processes in parallel
sleep 0.05
done
wait
# print own CPU usage after all spawned processes completed
top -b -n 1 -u "$own" | awk -v user=$own -v CPUS=$cpus 'NR>7 { sum += $9; } END { print user, sum, sum/CPUS; }'
这是一个稍微修改过的版本,用于打印 CPU 使用率全部可用用户(但跳过 CPU 使用率为零的用户),showAllPerUserCPU.sh:
own=$(id -nu)
cpus=$(lscpu | grep "^CPU(s):" | awk '{print $2}')
for user in $(getent passwd | awk -F ":" '{print $1}' | sort -u)
do
# print other user's CPU usage in parallel but skip own one because
# spawning many processes will increase our CPU usage significantly
if [ "$user" = "$own" ]; then continue; fi
(top -b -n 1 -u "$user" | awk -v user=$user -v CPUS=$cpus 'NR>7 { sum += $9; } END { if (sum > 0.0) print user, sum, sum/CPUS; }') &
# don't spawn too many processes in parallel
sleep 0.05
done
wait
# print own CPU usage after all spawned processes completed
top -b -n 1 -u "$own" | awk -v user=$own -v CPUS=$cpus 'NR>7 { sum += $9; } END { print user, sum, sum/CPUS; }'
第一列代表用户名,第二列代表聚合的 CPU 使用情况,第三列代表根据 CPU 核心数量标准化的 CPU 使用情况。
还有一个相关的脚本用于显示全部的每个用户的内存使用情况:showPerUserMem.sh
对于实时监控,只需通过watch
命令定期执行这些脚本即可。
要按 CPU 使用率排序,请将输出通过管道传输到sort -k2 -nr
.