edwinpaixao

cpu_usage

Oct 29th, 2016
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. #!/usr/bin/perl
  2. #
  3. # Copyright 2014 Pierre Mavro <[email protected]>
  4. # Copyright 2014 Vivien Didelot <[email protected]>
  5. # Copyright 2014 Andreas Guldstrand <[email protected]>
  6. #
  7. # Licensed under the terms of the GNU GPL v3, or any later version.
  8.  
  9. use strict;
  10. use warnings;
  11. use utf8;
  12. use Getopt::Long;
  13.  
  14. # default values
  15. my $t_warn = 50;
  16. my $t_crit = 80;
  17. my $cpu_usage = -1;
  18.  
  19. sub help {
  20. print "Usage: cpu_usage [-w <warning>] [-c <critical>]\n";
  21. print "-w <percent>: warning threshold to become yellow\n";
  22. print "-c <percent>: critical threshold to become red\n";
  23. exit 0;
  24. }
  25.  
  26. GetOptions("help|h" => \&help,
  27. "w=i" => \$t_warn,
  28. "c=i" => \$t_crit);
  29.  
  30. # Get CPU usage
  31. $ENV{LC_ALL}="en_US"; # if mpstat is not run under en_US locale, things may break, so make sure it is
  32. open (MPSTAT, 'mpstat 1 1 |') or die;
  33. while (<MPSTAT>) {
  34. if (/^Average:\s+all\s+(\d+\.\d+)\s+\d+\.\d+\s+(\d+\.\d+)/) {
  35. $cpu_usage = $1 + $2; # %usr + %sys
  36. last;
  37. }
  38. }
  39. close(MPSTAT);
  40.  
  41. $cpu_usage eq -1 and die 'Can\'t find CPU information';
  42.  
  43. # Print short_text, full_text
  44. printf "%.2f%%\n", $cpu_usage;
  45. printf "%.2f%%\n", $cpu_usage;
  46.  
  47. # Print color, if needed
  48. if ($cpu_usage >= $t_crit) {
  49. print "#FF0000\n";
  50. exit 33;
  51. } elsif ($cpu_usage >= $t_warn) {
  52. print "#FFFC00\n";
  53. }
  54.  
  55. exit 0;
Advertisement
Add Comment
Please, Sign In to add comment