Pak Jiddat

Read: In the name of thy Lord Who createth, Createth man from a clot. Read: And thy Lord is the Most Bounteous, Who teacheth by the pen, Teacheth man that which he knew not. Nay, but verily man is rebellious That he thinketh himself independent!. Lo! unto thy Lord is the return. (Sura Alalaq 96:8)

Finding CPU usage using top command

Created On: 10 Feb, 2017: 11:42:00 - Tags : server management

Url: http://askubuntu.com/questions/68741/finding-cpu-usage-from-top-command/687 54#68754

The top command can be used in combination with bash tools to find CPU usage.

The following command extracts CPU usage from the output of top command. The top command is run in batch mode so its output can be extracted:
cpu_usage=$(top -b -d1 -n1|grep -i "Cpu(s)"|head -c21|cut -d ' ' -f3|cut -d '%' -f1)

On some systems, in the above command f3 should be replaced with f2. The command returns the value for 'us', which is the percentage of the total CPU time spent running un-niced user processes. The output of the above command can be saved in a variable and sent by email using a command like mailx.

For example the following command will send an alert email to the system administrator using gmail server:


echo "Hello Admin. The CPU usage on server is $cpu_usage%. Please check!" > /tmp/mail_body.txt
mailx -s "CPU usage on server is more than 70%. Please check!." -r "reply_email" -S \
smtp="smtp.gmail.com:587" -S smtp-use-starttls -S smtp-auth=login -S \
smtp-auth-user="gmail_user" -S smtp-auth-password="gmail_password" -S ssl-verify=ignore recepiant_email < /tmp/mail_body.txt rm -rf /tmp/mail_body

Related Articles

  1. Running Plesk auto reapir
  2. Using Rsync over custom SSH port
  3. Installing latest version of Php
  4. Upgrading Postgresql from version 9.4 to 9.6
  5. Upgrading MySQL server from version 5.6 to 8.0
  6. Upgrading R from version 3.0 to 3.5
  7. Backing up and restoring LXD containers
  8. Resizing Linux root partitions without unmount on Google Cloud
  9. Running multiple versions of mailx command
  10. Getting /etc/rc.local file to work on Debian 9 (Stretch)
  11. Increasing number of concurrent connections for Proftp
  12. Changing ownership of symbolic link
  13. Configuring Apache to process html files as php
  14. Php server APIs
  15. Apache Multi Processing Modules (MPMs)
  16. Calculating the number of simultaneous connections supported by Apache
  17. Problem with copying large files to USB
  18. Importing Ldap configuration from file gives, "Wrong attributetype" error
  19. How To Change Account Passwords on an OpenLDAP Server
  20. Monitoring RAM usage on server
  21. Format of crontab file
  22. Force grub2 to not use UUID
  23. Automate scp command using sshpass