歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> 編寫Shell腳本查看Linux當前各用戶的cpu和memory消耗比例

編寫Shell腳本查看Linux當前各用戶的cpu和memory消耗比例

日期:2017/2/28 16:10:04   编辑:SHELL編程

為了方便自己查看CentOS上的各用戶cpu和內存的使用比例,寫了shell腳本。

viewUsage.sh

  1. #!/bin/bash
  2. #
  3. # view the cpu and memory consumption of each user at the current time.
  4. # chenqy 20101126 v0.9
  5. # chenqy 20110115 v1.0 :
  6. # added the sort option: --reverse --mem --cpu
  7. function viewconsumption {
  8. ps aux | grep -v 'PID' | sed 's/[ ][ ][ ]*/ /g' | cut -d " " -f1-4 | sort | awk '
  9. BEGIN{
  10. userid = "None"
  11. cpuUsage = 0
  12. memUsage = 0
  13. }
  14. {
  15. if(userid == $1) {
  16. cpuUsage += $3
  17. memUsage += $4
  18. } else {
  19. if (userid != "None") {
  20. printf("%s %4.1f %4.1f/n", userid, cpuUsage, memUsage)
  21. }
  22. userid = $1
  23. cpuUsage = $3
  24. memUsage = $4
  25. }
  26. }'
  27. }
  28. function printResult {
  29. awk '
  30. BEGIN {
  31. postcolor = "/033[0;39m"
  32. }
  33. {
  34. userid = $1
  35. cpuUsage = $2
  36. memUsage = $3
  37. if(cpuUsage >= 10 || memUsage >= 10) {
  38. # red color
  39. precolor = "/033[0;31m"
  40. }
  41. printf("%s%s /033[12G%4.1f /033[20G%4.1f%s/n", precolor, userid, cpuUsage, memUsage, postcolor)
  42. precolor = "/033[0;39m"
  43. }'
  44. }
  45. echo -e "USER /033[12G%CPU /033[20G%MEM"
  46. echo "--------- ------ -----"
  47. if [ "$1" == "--mem" ];then
  48. key="-k 3 -n"
  49. elif [ "$1" == "--cpu" ];then
  50. key="-k 2 -n"
  51. fi
  52. if [ "$1" == "--reverse" -o "$2" == "--reverse" ];then
  53. reverse="-r"
  54. fi
  55. viewconsumption|sed 's/[ ][ ][ ]*/ /g'|sort $key $reverse|printResult

使用說明:
#以下輸出均為“aix.unix-center.net”上的運行結果

1. 不使用參數,直接調用,默認排序為按user名升序,cpu或mem的使用率超過10%時以紅色字體顯示:
#提示:大寫字母開頭會排在小寫字母開頭前面

  1. tsingyee@aix bin# ./viewUsage.sh
  2. USER %CPU %MEM
  3. --------- ------ -----
  4. Michelle 48.2 0.0 <=這條記錄為紅色字體(cpu或mem的使用率超過10%)
  5. bookses 0.0 0.0
  6. centos1 0.0 0.0
  7. coolryx 0.0 0.0
  8. daemon 0.0 0.0
  9. dddfr 0.0 0.0
  10. erryqj 0.0 0.0
  11. firstdre 0.0 0.0
  12. freebsdj 0.0 0.0
  13. freshman 0.0 0.0
  14. geepz 0.0 0.0
  15. hanshanz 0.0 0.0
  16. he_pdz 0.0 0.0
  17. huangxue 0.0 0.0
  18. idlanhy 0.0 0.0
  19. jerry168 0.0 0.0
  20. junjieai 0.0 0.0
  21. junonly 0.0 0.0
  22. lichd 0.0 0.0
  23. lqjboy 0.0 0.0
  24. markcool 0.0 0.0
  25. mxdu 0.0 0.0
  26. nanman 0.0 0.0
  27. philippe 0.0 0.0
  28. piaoye06 0.0 0.0
  29. root 14.1 2.0 <=這條記錄為紅色字體(cpu或mem的使用率超過10%)
  30. spectre 0.0 0.0
  31. thorqq 0.0 0.0
  32. tsingyee 0.0 0.0
  33. uingei 0.0 0.0
  34. zhangdon 0.0 0.0
  35. zhangwb8 0.0 0.0
  36. zte_zxr1 0.0 0.0
  37. tsingyee@aix bin#
Copyright © Linux教程網 All Rights Reserved